<template>
    <div id="mesh" class="order-content">
        <div class="move-box2">
            <div id="silder-top" class="border-bottom-style">
                <el-row class="row-height top-row">
                    <el-col :span="12" class="col-box order-form-box" style="border-right: 1px solid #c9c9c9; padding-right: 10px">
                        <el-row class="form-row over-auto" style="height: calc(100% - 40px)">
                            <i
                                style="position: absolute; right: 0; font-size: 25px; z-index: 10"
                                class="el-icon-setting iconClass"
                                @click="openEntryGroup"
                            ></i>
                            <el-tabs type="card" v-model="activeKey" @tab-click="handleTabClick">
                                <el-tab-pane label="交易所指令" name="6" v-if="checkPermission('B_0315')">
                                    <div class="form-content" v-if="this.activeKey === '6'">
                                        <ExchangeOrder
                                            :refreshNumber="refreshNumber"
                                            :renderCount="renderCount['6']"
                                            :key="renderCount['6'] + 'exchange'"
                                            :detail="instructionCache['6']"
                                            :stockInfoCache="stockInfoCache['6']"
                                            @getOrderDirection="getOrderDirection"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>

                                <el-tab-pane label="北交所/股转指令" name="11" v-if="checkPermission('B_0324')">
                                    <div class="form-content" v-if="this.activeKey === '11'">
                                        <ExchangeOrder
                                            :isBSE="true"
                                            :renderCount="renderCount['11']"
                                            :key="renderCount['11'] + 'BSE'"
                                            :detail="instructionCache['11']"
                                            :stockInfoCache="stockInfoCache['11']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane label="转融通指令" name="14" v-if="checkPermission('B_0316')">
                                    <div class="form-content" v-if="this.activeKey === '14'">
                                        <RefinancingRiskOrder
                                            :renderCount="renderCount['14']"
                                            :key="renderCount['14']"
                                            :detail="instructionCache['14']"
                                            :stockInfoCache="stockInfoCache['14']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>

                                <el-tab-pane label="网下申购" name="9" v-if="checkPermission('B_0317')">
                                    <div class="form-content" v-if="this.activeKey === '9'">
                                        <!-- 网下申购指令表单 -->
                                        <OfflineSubscribeForm
                                            :renderCount="renderCount['9']"
                                            :key="renderCount['9']"
                                            :detail="instructionCache['9']"
                                            :stockInfoCache="stockInfoCache['9']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane label="债券一级投标" name="10" v-if="checkPermission('B_0318')">
                                    <div class="form-content" v-if="this.activeKey === '10'">
                                        <PrimaryBondOrder
                                            :renderCount="renderCount['10']"
                                            :key="renderCount['10'] + 'PrimaryBondOrder'"
                                            :detail="instructionCache['10']"
                                            :stockInfoCache="stockInfoCache['10']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                                <!-- 非标试算 -->
                                <el-tab-pane name="20" label="非标试算">
                                    <div class="form-content" v-if="this.activeKey === '20'">
                                        <OffstandardForm
                                            :key="renderCount['20']"
                                            :detail="instructionCache['20']"
                                            :stockInfoCache="stockInfoCache['20']"
                                            @getOrderForm="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane label="期货指令" name="7" v-if="checkPermission('B_0319')">
                                    <div class="form-content" v-if="this.activeKey === '7'">
                                        <FuturesOrder
                                            :renderCount="renderCount['7']"
                                            :key="renderCount['7']"
                                            :stockInfoCache="stockInfoCache['7']"
                                            :detail="instructionCache['7']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                            @getContractMulti="getContractMulti"
                                            @getFutureRatio="getFutureRatio"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane name="2" label="银行间债券" v-if="checkPermission('B_0320')">
                                    <div class="form-content" v-if="this.activeKey === '2'">
                                        <BankZQ
                                            :renderCount="renderCount['2']"
                                            :key="renderCount['2']"
                                            :stockInfoCache="stockInfoCache['2']"
                                            :detail="instructionCache['2']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane name="4" label="银行间回购" v-if="checkPermission('B_0321')">
                                    <div class="form-content" v-if="this.activeKey === '4'">
                                        <BankHG
                                            :renderCount="renderCount['4']"
                                            :key="renderCount['4']"
                                            :stockInfoCache="stockInfoCache['4']"
                                            :detail="instructionCache['4']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                        />
                                        <div class="pledgeTable">
                                            <span class="title" style="color: #575757">已选质押券:</span>
                                            <div style="margin-top: 5px">
                                                <vxe-table
                                                    :data="selectedList"
                                                    border
                                                    size="mini"
                                                    style="width: 100%"
                                                    height="100%"
                                                    auto-resize
                                                    resizable
                                                    :resizable-config="{ minWidth: '60' }"
                                                    show-header-overflow
                                                    :filter-config="{ iconNone: 'el-icon-search', iconMatch: 'el-icon-search' }"
                                                    header-align="center"
                                                >
                                                    <vxe-column
                                                        v-for="(item, index) in selectedPledgePositionsListMsg.title"
                                                        :key="index + item.val"
                                                        :field="item.val"
                                                        :title="item.name"
                                                        :sortable="item.sortable"
                                                        :column-config="{ isHover: true }"
                                                        :row-config="{ isHover: true }"
                                                        :filters="item.filters"
                                                        :filter-method="filterHandler"
                                                        show-overflow
                                                        :min-width="item.minWidth"
                                                        :width="item.width"
                                                        :fixed="item.fixed"
                                                    >
                                                        <template #filter="{ $panel, column }" v-if="['stockCode', 'stockNameSt'].includes(item.val)">
                                                            <div>
                                                                <el-input
                                                                    class="my-input"
                                                                    type="type"
                                                                    v-for="(option, index) in column.filters"
                                                                    :key="index"
                                                                    v-model="option.data"
                                                                    @input="$panel.changeOption($event, !!option.data, option)"
                                                                />
                                                            </div>
                                                        </template>

                                                        <template slot-scope="scope">
                                                            <el-button
                                                                v-if="item.val === 'operate'"
                                                                type="primary"
                                                                icon="el-icon-close"
                                                                @click="handleDelSelect(scope.row)"
                                                                size="mini"
                                                                class="tableButton"
                                                            ></el-button>
                                                            <!-- 券面总额 -->
                                                            <RiskInputNumber
                                                                v-else-if="item.val === 'totalFacePrice'"
                                                                :input="scope.row.totalFacePrice"
                                                                :field="'totalFacePrice'"
                                                                :precision="2"
                                                                :maxlength="15"
                                                                @getInputNumber="getInputNumber(arguments, scope.row)"
                                                            >
                                                            </RiskInputNumber>

                                                            <!-- 质押比率 -->
                                                            <RiskInputNumber
                                                                v-else-if="item.val === 'pledgeRatio'"
                                                                :input="scope.row.pledgeRatio"
                                                                :field="'pledgeRatio'"
                                                                :precision="2"
                                                                :inputAfter="'%'"
                                                                :maxlength="15"
                                                                @getInputNumber="getInputNumber(arguments, scope.row)"
                                                            >
                                                            </RiskInputNumber>

                                                            <!-- 到期金额 -->
                                                            <RiskInputNumber
                                                                v-else-if="item.val === 'balance'"
                                                                :input="scope.row.balance"
                                                                :field="'balance'"
                                                                :disabled="true"
                                                                :maxlength="15"
                                                                :precision="2"
                                                                @getInputNumber="getInputNumber(arguments, scope.row)"
                                                            >
                                                            </RiskInputNumber>

                                                            <span
                                                                v-else-if="['currentAmount', 'facePrice', 'totalPrice', 'balance'].includes(item.val)"
                                                                style="float: right"
                                                            >
                                                                {{ scope.row[item.val] != undefined ? numberFormat(scope.row[item.val], 2) : '--' }}
                                                            </span>

                                                            <span v-else-if="item.val === 'endDate'" style="display: block; text-align: center">
                                                                {{ dateFormat(scope.row[item.val]) || '--' }}
                                                            </span>

                                                            <span v-else>{{ scope.row[item.val] || '--' }}</span>
                                                        </template>
                                                    </vxe-column>
                                                </vxe-table>
                                            </div>
                                        </div>
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane name="8" label="场外基金指令" v-if="checkPermission('B_0322')">
                                    <div class="form-content" v-if="this.activeKey === '8'">
                                        <!-- <OverCounterFundOrder
                                    :key="renderCount['8']"
                                    :stockInfoCache="stockInfoCache['8']"
                                    :detail="instructionCache['8']"
                                    @handleSettingValue="handleSettingValue(arguments)"
                                    @getStockInfo="getStockInfo(arguments)"
                                /> -->
                                        <CWOpenForm
                                            :key="renderCount['8']"
                                            :outStockInfoCache="stockInfoCache['8']"
                                            :detail="instructionCache['8']"
                                            @handleSettingValue="handleSettingValue(arguments)"
                                            @getStockInfo="getStockInfo(arguments)"
                                            @getIntoStockInfo="getIntoStockInfo"
                                        />
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane name="5" label="存款" v-if="checkPermission('B_0323')">
                                    <div class="form-content" v-if="this.activeKey === '5'">
                                        <div v-if="instructionCache['5'] && instructionCache['5'].orderDirection == 'i'">
                                            <CkPaid
                                                :renderCount="renderCount['5']"
                                                :key="renderCount['5']"
                                                :stockInfoCache="stockInfoCache['5']"
                                                :paidDetail="instructionCache['5']"
                                                @handleSettingValue="handleSettingValue(arguments)"
                                                @getStockInfo="getStockInfo(arguments)"
                                            >
                                            </CkPaid>
                                        </div>
                                        <div v-else>
                                            <CK
                                                :renderCount="renderCount['5']"
                                                :key="'CK'"
                                                :stockInfoCache="stockInfoCache['5']"
                                                :detail="instructionCache['5']"
                                                :isMesh="true"
                                                @handleSettingValue="handleSettingValue(arguments)"
                                                @getStockInfo="getStockInfo(arguments)"
                                            />
                                        </div>
                                    </div>
                                </el-tab-pane>

                                <!-- ETF指令 -->
                                <el-tab-pane name="15" label="ETF指令">
                                    <div class="form-content" v-if="this.activeKey === '15'">
                                        <ETFForm
                                            :key="renderCount['15']"
                                            :detail="instructionCache['15']"
                                            :showIcon="true"
                                            @getOrderForm="handleSettingValue(arguments)"
                                            @getETFBasicInfo="getStockInfo(arguments)"
                                        />
                                    </div>
                                </el-tab-pane>
                            </el-tabs>
                        </el-row>
                        <el-row class="form-row" style="float: right">
                            <el-select style="width: 150px; margin-right: 10px" v-model="directMode" size="mini" @change="handleDirectModeChange">
                                <el-option label="有序从严控制" value="0">有序从严控制</el-option>
                                <el-option label="有序非从严控制" value="1">有序非从严控制</el-option>
                                <el-option label="无序从严控制" value="2">无序从严控制</el-option>
                                <el-option label="无序非从严控制" value="3">无序非从严控制</el-option>
                            </el-select>
                            <el-button name="reset" @click="handleResetForm" size="mini">重置</el-button>
                            <el-button name="calc" v-if="this.activeKey === '15'" @click="handleETFCalc" type="primary" size="mini">计算</el-button>
                            <el-button name="test" @click="handleTest" type="primary" size="mini">试算</el-button>
                            <el-button name="add" v-if="showType && activeKey !== '20'" type="primary" size="mini" @click="handleAdd">添加</el-button>
                            <el-button
                                name="edit"
                                v-else
                                type="primary"
                                :style="activeKey === '20' ? 'display: none' : ''"
                                size="mini"
                                @click="handleUpdate"
                                >修改</el-button
                            >
                        </el-row>
                    </el-col>

                    <!-- 非标试算导入 -->
                    <el-col v-if="activeKey === '20'" :span="12" class="col-box security-box over-auto" style="padding-left: 10px">
                        <div style="float: right; display: flex">
                            <el-upload
                                ref="uploadRef-2"
                                :action="uploadURL"
                                :headers="requestHead"
                                with-credentials
                                multiple
                                :file-list="fileList"
                                :before-upload="beforeUpload"
                                :on-success="
                                    (res, file) => {
                                        return handleAvatarSuccess(res, file);
                                    }
                                "
                            >
                                <el-button type="primary" size="mini">导入</el-button>
                            </el-upload>
                            <el-button type="default" size="mini" style="margin-left: 10px" @click="handleExportOff">下载模板</el-button>
                        </div>
                        <div style="display: flex; align-items: center; margin-bottom: 5px; height: 30px">
                            <h3 class="title">非标试算列表：</h3>
                        </div>
                        <el-row class="form-row riskTableHeight2">
                            <RiskTableP
                                ref="risk-table"
                                :tableData="tableDataOff"
                                :tableConfig="tableConfigOff"
                                :column="columnsOff"
                                v-loading="tableLoading"
                                style="height: 100%"
                            >
                            </RiskTableP>
                        </el-row>
                        <el-row class="form-row" style="line-height: 38px">
                            <el-button name="batchCalc" size="mini" type="primary" @click="handleRiskCalculateOff">风险试算</el-button>
                        </el-row>
                    </el-col>
                    <el-col v-else :span="12" class="col-box security-box over-auto" style="padding-left: 10px">
                        <div style="float: right">
                            <el-button name="refresh" type="primary" size="mini" @click="handleRefresh('1')">刷新</el-button>
                            <el-button v-authCode="B_0224" type="default" size="mini" @click="importDialog = true">导入</el-button>
                            <el-button v-authCode="B_0225" type="primary" size="mini" @click="handleExport">导出</el-button>
                        </div>
                        <div style="display: flex; align-items: center; margin-bottom: 5px; height: 30px">
                            <h3 class="title">风险试算列表：</h3>
                            <h3 style="padding-left: 50px">
                                默认成交
                                <el-switch
                                    id="dealModeSwitch"
                                    :value="dealMode"
                                    @change="handleDealModeChange"
                                    @input="handleSwitchClick"
                                    active-color="#13ce66"
                                    inactive-color="#eaecf0"
                                    active-value="1"
                                    inactive-value="0"
                                >
                                </el-switch>
                            </h3>
                        </div>
                        <!--  -->
                        <el-row class="form-row" :class="activeKey == '4' ? 'riskTableHeight1' : 'riskTableHeight2'">
                            <!-- <risk-table :msg="instTableMsg" @handleBtn="handleInstTableSelect" @handleChecked="selectChangeEvent"></risk-table> -->
                            <vxe-table
                                class="instTable"
                                :data="instDataSource"
                                border
                                style="width: 100%"
                                @checkbox-all="selectChangeEvent"
                                @checkbox-change="selectChangeEvent"
                                :auto-resize="true"
                                height="100%"
                                resizable
                                :resizable-config="{ minWidth: '50' }"
                                show-header-overflow
                                :key="listKey"
                                header-align="center"
                            >
                                <vxe-column type="checkbox" width="50" fixed="left" align="center"></vxe-column>
                                <vxe-column field="fundCode" title="产品代码/名称" show-overflow width="180">
                                    <!-- <template slot-scope="scope">
                <span>{{ DictionConstUtil.FNFundShowCode(scope.row.fundCode) + '/' + scope.row.fundNameSt }}</span>
              </template> -->
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.fundCode + '/' + scope.row.fundNameSt }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="assetCode" title="资产单元编号/名称" show-overflow width="150" v-show="SHOW_SECURITY">
                                    <template slot-scope="scope">
                                        <span>{{ (scope.row.assetCode || '--') + '/' + (scope.row.assetName || '--') }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="fundAccountCode" title="组合编码/名称" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ (scope.row.fundAccountCode || '--') + '/' + (scope.row.fundAccountName || '--') }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="stockCode" title="证券(合约|金融产品)代码/名称" show-overflow min-width="250">
                                    <template slot-scope="scope">
                                        <span>{{ (scope.row.stockCode || '') + '/' + (scope.row.stockNameSt || scope.row.stockName || '') }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="instType" title="指令类型" show-overflow min-width="110">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.instType ? instTypeMap[scope.row.instType] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="exchangeType" title="交易所指令类型" show-overflow min-width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.exchangeType ? exchangeTypeMap[scope.row.exchangeType] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="orderDirection" title="委托方向" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.orderDirection ? OrderDirection[scope.row.orderDirection] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>

                                <vxe-column field="targetType" title="目标类型" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.targetType ? targetTypePojo[scope.row.targetType] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="instructionTypeName" title="业务类型" show-overflow width="110">
                                    <template slot-scope="scope">
                                        <span>{{
                                            scope.row.instructionTypeName ? AllBusinessTypeMap[scope.row.instructionTypeName] || '--' : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="investType" title="投资类型" show-overflow min-width="110" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.investType ? Invest.investType[scope.row.investType] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="orderPrice" title="指令(净价)价格" show-overflow min-width="160">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.orderPrice != undefined ? numberFormat(scope.row.orderPrice, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="fullPrice" title="全价价格" show-overflow min-width="120">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.fullPrice != undefined ? numberFormat(scope.row.fullPrice, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="orderAmount" title="指令(融出|全价)数量(股/张/份)" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.orderAmount != undefined ? numberFormat(scope.row.orderAmount) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="orderBalance" title="指令(合约|回购|存款|净价)金额" show-overflow min-width="220">
                                    <template slot-scope="scope">
                                        <span v-if="scope.row.instType === '7'" style="float: right">
                                            <!-- {{ scope.row.orderBalance != undefined ? numberFormat(Number(scope.row.orderBalance) * contractMulti, 2) : '--' }} -->
                                            {{ scope.row.orderBalances != undefined ? numberFormat(scope.row.orderBalances) : '--' }}
                                        </span>
                                        <span v-else style="float: right">{{
                                            scope.row.orderBalance != undefined ? numberFormat(scope.row.orderBalance, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="totalInterest" title="总应计利息" show-overflow min-width="100">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.totalInterest != undefined ? numberFormat(scope.row.totalInterest, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="fullBalance" title="全价金额" show-overflow min-width="120">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.fullBalance != undefined ? numberFormat(scope.row.fullBalance, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="yield" title="到期收益率" show-overflow min-width="120">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{ scope.row.yield != undefined ? numberFormat(scope.row.yield, 2) : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="earnestBalance" title="申购定金" show-overflow min-width="220">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.earnestBalance != undefined ? numberFormat(scope.row.earnestBalance, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="destCombiId" title="转入组合编码" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.destCombiId || '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="destCombiName" title="转入组合名称" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.destCombiName || '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="destSecurityCode" title="转入证券代码" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.destSecurityCode || '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="destSecurityName" title="转入证券名称" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.destSecurityName || '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="bulkType" title="巨额赎回" show-overflow min-width="150">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{ scope.row.bulkType ? Invest.bulkType[scope.row.bulkType] : '--' }}</span>
                                    </template>
                                </vxe-column>

                                <vxe-column field="clearSpeed" title="清算速度" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <!-- <span>{{ scope.row.clearSpeed === '1' ? 'T+1' : 'T+0' }}</span> -->
                                        <span style="float: right">{{
                                            scope.row.clearSpeed === '1' ? 'T+1' : scope.row.clearSpeed === '0' ? 'T+0' : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="fullPrice" title="全价价格" show-overflow width="110">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.fullPrice != undefined ? numberFormat(scope.row.fullPrice, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="stockFaceBalance" title="券面总额" show-overflow width="110">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.stockFaceBalance != undefined ? numberFormat(scope.row.stockFaceBalance, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="firstSettleDate" title="结算日期" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="startDate" title="起息日" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="endSettleDate" title="到期日期" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="orderRate" title="回购利率(%)" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.orderRate != undefined ? numberFormat(scope.row.orderRate, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="curName" title="币种" show-overflow width="120" :formatter="formatterCell"> </vxe-column>
                                <vxe-column field="marketCode" title="交易市场" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span>{{ marketCodePojo[scope.row.marketCode] }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="orderPriceType" title="价格模式" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.orderPriceType ? investPriceSelectData[scope.row.orderPriceType] : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="depositType" title="存款类型" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.depositType ? DepositType[scope.row.depositType] || '--' : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="depositRate" title="存款利率(%)" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{
                                            scope.row.depositRate != undefined ? numberFormat(scope.row.depositRate, 2) : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="advanceLimitFlag" title="提前支取限制" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{
                                            scope.row.advanceLimitFlag ? advanceLimitFlagType[scope.row.advanceLimitFlag] || '--' : '--'
                                        }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="noticeDays" title="通知天数" show-overflow width="120" :formatter="formatterCell" align="right">
                                </vxe-column>
                                <vxe-column field="deadline" title="期限(天)" show-overflow width="120" :formatter="formatterCell" align="center">
                                </vxe-column>
                                <vxe-column field="rate" title="费率(%)" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{ scope.row.rate != undefined ? numberFormat(scope.row.rate, 2) : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="opponentCode" title="交易对手" :formatter="formatterOpponent" show-overflow width="120">
                                </vxe-column>
                                <vxe-column field="winningRate" title="预估中签率" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span style="float: right">{{ scope.row.winningRate ? numberFormat(scope.row.winningRate, 2) : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="tenderWay" title="投标方式" show-overflow width="120" :formatter="formatterCell">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.tenderWay ? Invest.tenderWayType[scope.row.tenderWay] : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="subject" title="招标标的" show-overflow width="120">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.subject ? Invest.bidSubjectType[scope.row.subject] : '--' }}</span>
                                    </template>
                                </vxe-column>
                                <vxe-column field="listDate" title="上市日期" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="payDate" title="缴款日期" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="drawDate" title="支取日期" show-overflow width="120" :formatter="formatDate" align="center">
                                </vxe-column>
                                <vxe-column field="receiptNo" title="存单号" show-overflow width="120" :formatter="formatterCell" align="center">
                                </vxe-column>
                                <vxe-column field="drawInterest" title="利息金额" show-overflow width="120" :formatter="formatterCell" align="center">
                                </vxe-column>
                                <vxe-column field="advanceType" title="支取类型" show-overflow width="120" :formatter="formatterCell2" align="center">
                                </vxe-column>
                                <vxe-column title="操作" width="110px" fixed="right">
                                    <template slot-scope="scope">
                                        <el-button
                                            icon="el-icon-edit"
                                            class="tableButton"
                                            size="mini"
                                            type="primary"
                                            @click="handleShowEdit(scope.row)"
                                        ></el-button>
                                        <el-button
                                            icon="el-icon-delete"
                                            class="tableButton"
                                            size="mini"
                                            type="danger"
                                            @click="handleDelete(scope.row)"
                                        ></el-button>
                                    </template>
                                </vxe-column>
                            </vxe-table>
                        </el-row>
                        <el-row class="title" v-show="activeKey == '4'" style="margin: 5px 0">可质押债券:</el-row>

                        <el-row class="form-row pledgeTable" v-show="activeKey == '4'">
                            <!-- <div class="pledgeTable"> -->
                            <vxe-table
                                :key="pledgeTableKey"
                                :data="pledgePositionsListMsg.returnData.data"
                                border
                                size="mini"
                                style="width: 100%"
                                height="100%"
                                auto-resize
                                resizable
                                :resizable-config="{ minWidth: '60' }"
                                show-header-overflow
                                @filter-change="handleFilterPledge"
                                :filter-config="{ remote: true, iconNone: 'el-icon-search', iconMatch: 'el-icon-search' }"
                                header-align="center"
                            >
                                <vxe-column
                                    v-for="(item, index) in pledgePositionsListMsg.title"
                                    :key="index + item.val"
                                    :field="item.val"
                                    :title="item.name"
                                    :sortable="item.sortable"
                                    :column-config="{ isHover: true }"
                                    :row-config="{ isHover: true }"
                                    :filters="item.filters"
                                    show-overflow
                                    :min-width="item.minWidth"
                                    :width="item.width"
                                    :fixed="item.fixed"
                                >
                                    <template #filter="{ $panel, column }" v-if="['stockCode', 'stockNameSt'].includes(item.val)">
                                        <div>
                                            <el-input
                                                class="my-input"
                                                type="type"
                                                v-for="(option, index) in column.filters"
                                                :key="index"
                                                v-model="option.data"
                                                @input="$panel.changeOption($event, !!option.data, option)"
                                            />
                                        </div>
                                    </template>

                                    <template slot-scope="scope">
                                        <el-button
                                            v-if="item.val === 'operate'"
                                            type="primary"
                                            icon="el-icon-check"
                                            @click="handleSelect(scope.row)"
                                            :disabled="scope.row.disabled"
                                            size="mini"
                                            class="tableButton"
                                        ></el-button>
                                        <span
                                            v-else-if="['currentAmount', 'facePrice', 'totalPrice', 'balance'].includes(item.val)"
                                            style="float: right"
                                        >
                                            {{ scope.row[item.val] != undefined ? numberFormat(scope.row[item.val], 2) : '--' }}
                                        </span>

                                        <span v-else-if="item.val === 'endDate'" style="display: block; text-align: center">
                                            {{ dateFormat(scope.row[item.val]) || '--' }}
                                        </span>

                                        <span v-else>{{ scope.row[item.val] || '--' }}</span>
                                    </template>
                                </vxe-column>
                            </vxe-table>
                            <!-- </div> -->

                            <!-- <risk-table
                        :msg="pledgePositionsListMsg"
                        @handleBtn="handleSelect"
                        @getList="getPledgeList"
                        @handleFilter="handleFilterPledge"
                    ></risk-table> -->
                        </el-row>
                        <el-row class="form-row" style="line-height: 38px">
                            <el-pagination
                                v-show="activeKey == '4'"
                                style="float: right; padding: 4px 0 !important"
                                background
                                @current-change="getPledgeList"
                                layout="total, prev, pager, next"
                                :current-page="pages.currentPage"
                                :page-size="pages.pageSize"
                                :total="pledgePositionsListMsg.returnData.total"
                            >
                            </el-pagination>
                            <el-button name="batchCalc" size="mini" type="primary" @click="handleRiskCalculate">风险试算</el-button>
                        </el-row>
                    </el-col>
                </el-row>
                <div class="move-btn2" v-move-lengthways></div>
            </div>
            <div class="silder-bottom">
                <el-row class="row-height bottom-row">
                    <el-col class="col-box">
                        <h3 class="title">
                            <el-row style="display: flex; align-items: center; margin-bottom: 5px">
                                <el-col :span="5">
                                    风控结果: <status-tag :code="riskResult"></status-tag>
                                    <span style="color: red; padding-left: 5px">{{ showEntryText() }}</span>
                                </el-col>
                                <el-col :span="6">
                                    <span>试算/下单时间: </span>
                                    <span style="color: red">{{ calcTime }}</span>
                                </el-col>
                                <el-col :span="4">
                                    <span>计算耗时: </span>
                                    <span style="color: red">{{ takeTime }}</span>
                                </el-col>
                                <el-col :span="3"
                                    >条目检查数:
                                    <span v-show="riskResultSourceList.length" style="color: red">{{
                                        this.riskResultSourceList.length
                                    }}</span></el-col
                                >
                                <el-col :span="6">
                                    <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                                    <el-button
                                        v-show="riskResultTable.length"
                                        style="margin-right: 15px"
                                        type="primary"
                                        size="mini"
                                        @click="handleExportResult"
                                        >导出</el-button
                                    >
                                    <el-checkbox v-model="thresholdTypeFilter['1']" @change="handelThresholdTypeFilter('1')">显示触警</el-checkbox>
                                    <el-checkbox v-model="thresholdTypeFilter['0']" @change="handelThresholdTypeFilter('0')">显示合规</el-checkbox>
                                </el-col>
                            </el-row>
                        </h3>

                        <TrailResult
                            :riskResultTable="riskResultTable"
                            :showFieldList="showFieldList"
                            :tableColumns="tableColumns"
                            :calcLoading="calcLoading"
                        />
                    </el-col>
                </el-row>
            </div>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="MESH_LAYOUT"
            @on-submit="onSubmit"
        />
        <EntryGroupSetting
            v-if="transDialog"
            :resourceCode="resourceCode"
            :transDialog="transDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />

        <RiskCalculateImport
            v-if="importDialog"
            :importDialog="importDialog"
            :importButtonDisabled="importButtonDisabled"
            @closeImportDialog="closeImportDialog"
            @settingImportValue="settingImportValue"
        ></RiskCalculateImport>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import DictionConstUtil, { SGU_CACHE, objToArr } from '@/utils/diction-const-util';
import Invest from '@/common/dict/invest';
import {
    UUID,
    NumberToWords,
    getCurrentPageData,
    PrefixInteger,
    numberFormat,
    unitShow,
    dateFormat,
    sortBy,
    checkPermission,
    accMul,
    getConfigItem,
    accDiv,
} from '@/utils/tools';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import RiskResult from '@/pages/risk-measure/components/risk-result.vue';
import { getActiveMenuCode, getUser } from '@/utils/user-util';
import ExchangeOrder from './components/exchange-order.vue';
import FuturesOrder from './components/futrues-order.vue';
import BankHG from './components/bank-hg.vue';
import BankZQ from './components/bank-zq.vue';
import OverCounterFundOrder from './components/cwOpenOrder/over-count-fund-form.vue';
import PrimaryBondOrder from './components/primary-bond-bid-order.vue';
import CK from './components/ck.vue';
import { foundStockExistAsync, getBusinessType, getFutureContractMulti, getSystemTradeDay } from './api';
import { getMarketPrice, trialCalculate } from '@/common/api/instruction';
import moment from 'moment';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { exportExcel, exportExcels } from '@/utils/excel-utils';
import RiskCalculateImport from '@/pages/risk-time/components/risk-calculate-import.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import ColumnUtil from './utils/column-util';
import EntryGroupSetting from './components/entry-group-seting.vue';
import CWOpenForm from './components/cw-open-form.vue';
import FundTransferForm from './components/cwOpenOrder/fund-transfer-form.vue';
import OfflineSubscribeForm from './components/offline-subscribe-form.vue';
import RefinancingRiskOrder from './refinancing/refinancing-risk-order.vue';
import CkPaid from './components/ck-paid.vue';
import TrailResult from './components/trail-result.vue';
import ETFForm from './components/etf-form.vue';
import OffstandardForm from './components/offstandard-form.vue';
import { calculateEtfStock, getETFBasicInfo } from './api/etf';
import { downLoadFile } from '@/utils/request';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, TableConfigVO } from '@/common/vo';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
type TFieldItem = { id: string; content: string };

@Component({
    name: 'InstructionMesh',
    components: {
        RiskTable,
        StatusTag,
        BranchTag,
        RiskResult,
        ExchangeOrder,
        RefinancingRiskOrder,
        FuturesOrder,
        BankHG,
        BankZQ,
        OverCounterFundOrder,
        CK,
        CkPaid,
        RiskTableLayout,
        RiskCalculateImport,
        RiskInputNumber,
        EntryGroupSetting,
        PrimaryBondOrder,
        CWOpenForm,
        FundTransferForm,
        OfflineSubscribeForm,
        TrailResult,
        ETFForm,
        OffstandardForm,
        RiskTableP,
    },
})
// 风险试算
export default class InstructionMesh extends Vue {
    ColumnUtil = new ColumnUtil();
    DictionConstUtil = new DictionConstUtil();
    numberFormat = numberFormat;
    checkPermission = checkPermission;
    dateFormat = dateFormat;
    unitShow = unitShow;
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    BASE_URL_API = getConfigItem('BASE_URL_API');

    advanceLimitFlagType = {
        '1': '不可提前支取',
        '2': '可提前支取无利息损失',
        '3': '可提前支取但损失利息',
        '4': '无条件可提前支取',
    };

    /**
     * 试算所有的业务类型
     */
    AllBusinessTypeMap: any = {
        '1': '交易所网上',
        C: '网下申购',
        E: '交易所大宗交易',
        I: '上交易固定收益平台',
        D: '债券一级市场',
        J: '上交所固定收益平台做市',
        '5': '场内开基业务',
        '4': '期货业务',
        '2': '银行间业务',
        A: '开放式基金',
        B: '存款类',
    };

    exchangeTypeMap = {
        '1': '股票指令',
        '2': '转融通指令',
        '3': '债券指令',
        '4': '基金指令',
        '5': '权证指令',
        '6': '回购指令',
        '8': '上交所固定收益平台指令',
    };

    instTypeMap = {
        '1': '交易所债券',
        '2': '银行间债券指令',
        '3': '交易所回购指令',
        '4': '银行间回购指令',
        '5': '存款指令',
        '6': '交易所指令',
        '7': '期货指令',
        '8': '场外基金指令',
        '9': '网下申购指令',
        '10': '债券一级投标',
        '11': '北交所/股转指令',
        '14': '转融通指令',
        '15': 'ETF指令',
        '20': '非标指令',
    };

    clearSpeedType = {
        '0': 'T+0',
        '1': 'T+1',
    };

    // 价格模式
    investPriceSelectData = {
        // '1': '绝对价格',
        // '2': '不限价',
    };
    DepositType = {
        '1': '定期存款',
        '2': '通知存款',
        '3': '协议存款',
        '6': '次级债券',
    };

    activeKey: string = '6';
    instructionName: string = '交易所网上';

    instDataSource: any[] = []; // 风险试算列表详细数据

    resultDataSource: any[] = [];

    showType: boolean = true; // true显示添加按钮 false显示修改按钮
    selectedRowKeys: any[] = [];
    clickRowStype: string = ''; // 选中高亮
    showEntryGroupModal: boolean = false;
    calcLoading: boolean = false;
    thresholdTypeFilter: any = {
        '0': false,
        '1': true,
    };
    layoutModal: boolean = false;
    directMode: string = '0'; // 是否从严控制，默认0，从严
    Invest: any = new Invest();

    orginalData: any[] = []; //  试算列表

    instDataSourceCache: any[] = []; // 风险试算列表数据
    correspondingIndex: number = 0;
    updateInstruction: any = 0;
    tableKey: number = 0;
    listKey: number = 0;

    layoutDialog: boolean = false;

    importDialog: boolean = false;

    renderCount = {
        '1': 0,
        '2': 0,
        '3': 0,
        '4': 0,
        '5': 0,
        '6': 0,
        '7': 0,
        '8': 0,
        '9': 0,
        '10': 0,
        '11': 0,
        '14': 0,
        '15': 0,
        '20': 0,
    };

    // 下单类型转换
    InstTypePojo = {
        '1': '1',
        '2': '1',
        '3': '2',
        '4': '2',
        '5': '3',
        '6': '1',
        '7': '6',
        '8': '8',
        '9': '9',
        '11': '1',
        '14': '14',
        '15': '19',
        '20': '20',
    };

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据

    calcTime: string = ''; // 下单/试算时间

    takeTime: string | number = ''; // 计算耗时

    riskResult: string | number = ''; // 风控结果

    // 风控结果表数据
    riskResultTable: any[] = [];

    riskResultSourceList: any[] = [];

    // 试算结果
    testTable: any[] = [];

    // 风险试算结果
    riskTestTable: any[] = [];

    // 条目组穿梭框
    transDialog: boolean = false;

    // 模块详情穿梭框数据
    private tranColumns: any[] = [
        {
            label: '编号',
            prop: 'groupCode',
            width: 80,
        },
        {
            label: '名称',
            prop: 'groupName',
        },
    ];

    dataSourceLeft: any[] = [];
    dataSourceCalculateRight: any[] = [];
    dataSourceExcludeRight: any[] = [];
    selectKeyLeft: any[] = []; // 左边选中的key
    selectKeyCalculateRight: any[] = []; // 右边选中的key
    selectKeyExcludeRight: any[] = []; // 右边选中排除的key
    entryGroups: any[] = [];

    selectEntryGroupCode = {
        calculateEntryGroup: [],
        excludeEntryGroup: [],
    };
    resourceCode: string = '';

    instructionCache: any = {
        '1': {},
        '2': {},
        '3': {},
        '4': {},
        '5': {
            orderDirection: 'F',
        },
        '6': {},
        '7': {},
        '8': {},
        '9': {},
        '10': {},
        '11': {},
    };
    stockInfo: any = {};
    startTime: moment.Moment;
    stockInfoPojo: any = {};
    stockInfoCache: any = {};

    entryType = {}; // 风险类型字典

    compareDirection = {}; // 比较方向字典
    marketCodePojo: any = {};
    OrderDirection: any = {};
    targetTypePojo: any = {}; // 目标类型枚举对象

    // 已选质押券信息相关
    selectedPledgePositionsListMsg = {
        returnData: { data: [{}], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.selectedPledgeColumns,
        height: '100%',
        // 隐藏页码
        hidePage: true,
        checked: { on: false, option: false },
    };
    pledgePositionsList: any[] = [];

    // 可选质押券信息相关
    pledgePositionsListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.pledgeColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };
    // 分页
    pages = { currentPage: 1, pageSize: 25 };
    selectedList: any[] = [];
    pledgePOList: any[] = [];
    pledgeFilterList: any[] = [];
    stockCode2: string = '';
    stockName2: string = '';

    // 风险试算列表表格相关
    instTableMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.instTableColumns,
        height: '100%',
        hidePage: true, // 隐藏页码
        checked: { on: true, option: false },
    };

    // 全部表格列
    private tableColumns: any[] = [
        { content: '指令序号', id: 'instructionNo', sortable: false },
        { content: '产品代码', id: 'fundCode', sortable: false, align: 'left' },
        { content: '产品名称', id: 'fundNameSt', sortable: false, align: 'left' },
        { content: '证券/金融产品代码', id: 'stockCode', sortable: true, minWidth: 190, align: 'left' },
        { content: '证券/金融产品名称', id: 'stockNameSt', sortable: false, minWidth: 170, align: 'left' },
        { content: '条目编号', id: 'entryCode', sortable: true, align: 'left' },
        { content: '风险说明', id: 'entryName', sortable: false, align: 'left' },
        { content: '风险类型', id: 'entryType', sortable: false, align: 'center' },
        { content: '风控阈值', id: 'thresholdValue', sortable: false, align: 'right' },
        { content: '比较方向', id: 'compareType', sortable: false, align: 'center' },
        { content: '委托方向', id: 'orderDirection', sortable: false, align: 'center' },
        { content: '计算结果(单位)', id: 'calculateValue', sortable: false, align: 'right' },
        { content: '阈值类型', id: 'thresholdType', sortable: true, align: 'center' },
        { content: '可投余量', id: 'investableBalance', sortable: false, align: 'center' },
        { content: '最大可交易量', id: 'maxTradable', sortable: false, align: 'center' },
        { content: '最大可交易量(汇总)', id: 'maxTradableMerge', sortable: false, align: 'center' },
        { content: '静态条目KEY', id: 'entryKey', sortable: false, align: 'left' },
        { content: '分支详情', id: 'branchNum', sortable: false, align: 'center' },
    ];

    // 要显示的表格列
    showFieldList: any[] = [];

    // 已选择字段列表
    selectedFieldList: any[] = [];

    entryTypeArr: any[] = [];
    ThresholdTypeArr: any[] = [];

    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];

    // 图标dom
    iconDom: any = null;
    tradeDays: any[] = []; // 交易日
    tabloading: boolean = false;
    opponentCodeSelectData: any[] = [];
    dealMode: string = '1'; // 默认成交
    pledgeTableKey: number = 0;
    batchDirectMode: string = '4';
    dealModeDisabled: boolean = false; // 默认成交是否禁用
    intoStockInfo: any = {};
    contractMulti: number = 0; // 合约乘数
    refreshNumber: number = 0;
    marketPriceArr: any[] = [];
    hasFutureRatio: boolean = true; // 所选产品和证券是否含有期货保证金比例

    importButtonDisabled: boolean = false;
    assetList: any = [];
    fdAcList: any[] = [];
    stockTableData: any[] = []; // ETF成分股数据
    stockTableCalcState: boolean = false; // ETF成分股计算状态

    async mounted() {
        this.tableColumns = this.ColumnUtil.handleResultColumns(this.tableColumns, 'id');
        this.resourceCode = getActiveMenuCode().defaultActive;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        // 价格模式
        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPriceSelectData = DictionConstUtil.ListToPojo(priceTypeTemp);
        this.queryLayout();
        this.calcLoading = true;
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;

        this.marketCodePojo = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());
        this.OrderDirection = DictionConstUtil.ListToPojo(await DictionConstUtil.FNTradeDirection());
        this.targetTypePojo = DictionConstUtil.targetType;
        this.getUserSelectEntryGroupList();

        getSystemTradeDay().then(res => {
            this.tradeDays = res.map(item => Number(item)).sort((a, b) => a - b);
        });

        this.$axios.get('/dict/businessType/all').then(res => {
            let test = (this.AllBusinessTypeMap = DictionConstUtil.ListToPojo(res));
        });
        this.getOpponentCode('');

        this.uploadURL = this.BASE_URL_API + '/dataEngine/ht/nonStandard';
    }

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    formatterCell({ cellValue }) {
        return cellValue || '--';
    }

    formatterCell2({ cellValue }) {
        return this.advanceLimitFlagType[cellValue] || '--';
    }

    changeTable() {
        this.$nextTick(() => {
            let nodeName = [];
            let icon = [];
            if (!this.iconDom) {
                let obj = document.querySelector('.bottom-row');
                this.iconDom = obj.querySelectorAll('.vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < 8; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    // 自定义排序
    customSortMethod({ data, sortList }) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode.match('.*[A-Z]+.*') || ele.entryCode.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode' || property === 'stockCode') {
                YHList.sort(this.compare(property));
                NoYHlist.sort(this.compare(property));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(sortBy(property, order));
            }
        }
        return list;
    }

    compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }

    getContractMulti(arg: any) {
        this.contractMulti = arg;
    }

    getStockInfo(args: any) {
        this.stockInfo = args[0];
        this.stockInfoCache[args[1]] = this.stockInfo || {};
    }

    getIntoStockInfo(args: any) {
        this.intoStockInfo = args || {};
    }

    // 所选产品是否含有期货保证金比例
    getFutureRatio(args: any) {
        this.hasFutureRatio = args;
    }

    // 获取交易所指令的委托方向
    getOrderDirection(value: any) {
        if (!this.instructionCache['6']) {
            this.instructionCache['6'] = {};
        }
        this.instructionCache['6']['orderDirection'] = value;
    }

    /**
     * 指令事件回调
     */
    handleSettingValue(msg: any) {
        // 处理交易所指令，showType === 1 时，预估中签率 的百分号
        let data = JSON.parse(JSON.stringify(msg[0]));
        // if (msg[1] === '6' && msg[0] && (msg[0].showType == 1 || msg[0].showType == 3) && msg[0].winningRate) {
        //   data.winningRate = (Number(msg[0].winningRate.trim()) / 100).toString();
        // }
        // this.instructionCache[msg[1]] = JSON.parse(JSON.stringify(msg[0]));
        this.$set(this.instructionCache, msg[1], data);

        if (msg[1] == '4' && this.instructionCache[msg[1]].fundCode !== undefined) {
            // this.selectedList = [];
            // 清除可选质押券表格筛选条件
            this.pledgeFilterList = [];
            this.pledgeTableKey++;
            // 查询质押券信息
            // this.getPledgeList(this.pages);
            this.getPledgeList(1);
        }
    }

    getInputNumber(args: any, row: any) {
        let value = args[0];
        let field = args[1];
        row[field] = value;
        if (field === 'totalFacePrice') {
            // 质押数量 = 券面总额 * 10000 / 100
            row['pledgedQty'] = (Number(row['totalFacePrice'] || 0) * 10000) / 100;
            // 成交金额 = 券面总额 * 质押比率 / 100
            row['balance'] = (Number(row['totalFacePrice']) * Number(row['pledgeRatio'])) / 100;
        } else if (field === 'pledgeRatio') {
            row['balance'] = (Number(row['totalFacePrice']) * Number(row['pledgeRatio'])) / 100;
        }
        // this.pledgePOList = this.handleSelectdPledgeList(this.selectedList);
        this.instructionCache[4].selectedPledgePOList = this.selectedList;
    }

    handleTabClick(tab, event) {
        this.showType = true;
        // console.log(this.instructionCache[this.activeKey]);
    }

    handleSwitchClick(value) {
        if (!['0', '2'].includes(this.directMode)) {
            this.yh_message_warn('选择非从严计算模式, 仅支持开启模式');
        } else {
            if (this.dealMode === '0') {
                this.dealMode = '1';
            } else {
                this.dealMode = '0';
            }
        }
    }

    // 计算模式变化
    handleDirectModeChange(value: any) {
        // let switchObj = document.getElementById('dealModeSwitch');
        if (['0', '2'].includes(value)) {
            // 从严控制
            this.handleDealModeChange(this.dealMode);
            this.dealModeDisabled = false;
        } else {
            // 非从严控制
            this.batchDirectMode = this.directMode;
            this.dealModeDisabled = true;
            this.dealMode = '1';
        }
    }

    // 默认成交值变化事件
    handleDealModeChange(value: any) {
        if (value === '0') {
            // 默认成交关闭
            if (this.directMode === '0') {
                // 有序从严
                this.batchDirectMode = '6';
            } else if (this.directMode === '2') {
                // 无序从严
                this.batchDirectMode = '7';
            }
        } else {
            // 默认成交开启
            if (this.directMode === '0') {
                this.batchDirectMode = '4';
            } else if (this.directMode === '2') {
                this.batchDirectMode = '5';
            }
        }
    }

    // 重置按钮事件
    handleResetForm() {
        this.renderCount[this.activeKey] += 1;
        if (this.activeKey == '5') {
            this.instructionCache[this.activeKey] = {
                orderDirection: this.instructionCache[this.activeKey].orderDirection,
            };
        } else {
            this.instructionCache[this.activeKey] = null;
        }
        this.stockInfoCache[this.activeKey] = {};
        this.directMode = '0';
        // 触发渲染行为
        this.showType = true;
        this.pledgePositionsListMsg.returnData.data = [];
        this.pledgePositionsListMsg.returnData.total = 0;
        this.selectedList = [];
    }

    // 风险试算列表格 - 日期相关列转换
    formatDate({ cellValue, row, column }) {
        return cellValue ? moment(cellValue, 'YYYYMMDD').format('YYYY-MM-DD') : '--';
    }

    // 风险试算表格 - 产品代码列转换
    async formatFundCode({ cellValue, row, column }) {
        let showCode = await DictionConstUtil.FNFundShowCode(cellValue);
        return cellValue ? showCode + '/' + row.fundNameSt : '--/--';
    }

    handelThresholdTypeFilter() {
        this.riskResultTable = this.riskResultSourceList.filter(
            item => (this.thresholdTypeFilter['1'] && item.thresholdType !== '0') || (this.thresholdTypeFilter['0'] && item.thresholdType === '0')
        );
    }

    /* ************************* 质押券相关start *********************** */

    // 处理已选质押券数据
    handleSelectdPledgeList(selectedledgePOList: any) {
        let pledgePOList = this.selectedList.map(ele => {
            return {
                totalFacePrice: String(Number(ele.totalFacePrice || '0') * 10000 || ''),
                fundAccountCode: ele.fundAcCode,
                pledgeRatio: ele.pledgeRatio,
                pledgedQty: ele.pledgedQty,
                investType: ele.investType,
                marketCode: ele.marketCode,
                reportCode: ele.stockCode.split(' ')[0] || '',
            };
        });
        return pledgePOList;
    }
    // 质押券信息分页
    getPledgeList(pages) {
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.pledgeFilterList.length) {
            form = {
                fundCode: [this.instructionCache[4].fundCode],
                paging: { currentPage: pages, pageSize: 25 },
            };
        } else {
            form = {
                stockCode: this.stockCode2,
                stockNameSt: this.stockName2,
                fundCode: [this.instructionCache[4].fundCode],
                paging: { currentPage: pages, pageSize: 25 },
            };
        }
        // 获取产品持仓信息
        this.$axios.post('position/stock/pledge', form).then((res: any) => {
            this.pledgePositionsListMsg.returnData.data = res.list;
            this.pledgePositionsListMsg.returnData.total = res.total;
            this.handlePledgeList();
        });
    }

    handleFilterPledge({ column, property, values, datas, filterList, $event }) {
        this.pledgeFilterList = filterList;
        this.stockCode2 = '';
        this.stockName2 = '';
        if (filterList.length) {
            let code = filterList.find(ele => ele.property === 'stockCode');
            let name = filterList.find(ele => ele.property === 'stockNameSt');
            this.stockCode2 = code?.datas[0] || '';
            this.stockName2 = name?.datas[0] || '';
        }
        this.getPledgeList(1);
    }

    handlePledgeList() {
        let selectedPositionIds = this.selectedList.map(ele => Number(ele.positionId));
        this.pledgePositionsListMsg.returnData.data.forEach(ele => {
            if (selectedPositionIds.includes(ele.positionId)) {
                ele['disabled'] = true;
            } else {
                ele['disabled'] = false;
            }
        });
    }

    // 取消选中质押券事件
    handleDelSelect(row: any) {
        this.selectedList = this.selectedList.filter(item => item.positionId !== row.positionId);
        this.selectedPledgePositionsListMsg.returnData.data = this.selectedList;
        this.handlePledgeList();
    }

    // 选中质押券事件
    handleSelect(row: any) {
        let isExist = false;
        for (let i = 0; i < this.selectedList.length; i++) {
            if (this.selectedList[i]['custodianName'] !== row.custodianName) {
                isExist = true;
                break;
            }
        }
        if (isExist) {
            this.yh_message_warn('已选质押券必须属于同一托管机构！');
        } else {
            let obj = {
                totalFacePrice: row.totalPrice,
                pledgeRatio: '100',
                pledgedQty: row['currentAmount'],
                balance: '',
            };
            obj.balance = String((Number(obj.totalFacePrice || '0') * Number(obj.pledgeRatio || '0')) / 100);

            this.selectedList.unshift({ ...obj, ...row });
            this.handlePledgeList();
            this.selectedPledgePositionsListMsg.returnData.data = this.selectedList;
            this.instructionCache[4].selectedPledgePOList = this.selectedList;
            // this.handleSelectdPledgeList();
        }
    }

    /* ************************* 质押券相关end *********************** */

    /** **************************** ETF指令start ***************************** */
    handleETFCalc() {
        console.log('etf:');

        let etfBasicInfo = this.stockInfoCache['15'];
        let instruction = this.instructionCache['15'];
        const verifyParams: any = {
            fundCode: '产品代码',
            stockCode: '证券代码',
            orderAmount: '指令数量',
            orderBalance: '指令金额',
        };
        if (!instruction) {
            this.yh_message_warn('请填写相关信息');
            return;
        }
        for (const key in verifyParams) {
            if (!instruction[key]) {
                this.yh_message_warn(verifyParams[key] + '不可为空');
                return false;
            }
        }
        if (!etfBasicInfo) {
            // 没有选券的时候不调用计算接口
            return;
        }
        let form = {
            estimatecash: this.stockInfoCache['15']?.estimatecash || 0,
            execType: this.stockInfoCache['15']?.execType || '',
            fundCode: instruction.fundCode || '',
            instructionAmount: Number(instruction.orderAmount) || 0,
            instructionBalance: Number(instruction.instructionBalance) || 0,
            orderDirection: instruction.orderDirection || '',
            stockCode: etfBasicInfo?.stockCode || '',
            stockTargetType: instruction.targetType == '1' ? '2' : '1',
        };
        calculateEtfStock(form)
            .then(res => {
                this.stockTableData = res;
                this.stockTableCalcState = true;
                this.yh_message_success('计算完成');
            })
            .catch(() => {
                this.stockTableData = [];
                this.stockTableCalcState = false;
                // this.pages.total = 0;
            });
    }

    /** **************************** ETF指令end ***************************** */

    /* ****************************** 风险试算列表start ************************ */

    // 获取表格复选框选中数据
    private selectChangeEvent(val) {
        this.selectedRowKeys = [];
        val.selection.forEach(ele => {
            this.selectedRowKeys.push(ele.requestId);
        });
    }

    //   获取交易对手方信息
    async getOpponentCode(value: string) {
        await this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    formatterOpponent({ cellValue, row }) {
        // let info: any = this.opponentCodeSelectData.find(ele => ele.dictKey === cellValue);
        // return info ? info.dictKey + '/' + info.dictKeyName : '--';
        return cellValue ? cellValue + '/' + row.opponentName : '--';
    }

    // handleInstTableSelect(row: any) {
    //     console.log(row);
    //     if (row.type === '编辑') {
    //         this.handleShowEdit(row.row);
    //     } else {
    //         this.handleDelete(row.row);
    //     }
    // }

    // 添加数据到风险试算列表
    async handleAdd() {
        let instruction = JSON.parse(JSON.stringify(this.instructionCache[this.activeKey] || {}));

        let stockInfo = this.stockInfoCache[this.activeKey] || {};
        if (!instruction) {
            this.yh_message_warn('请填写相关信息');
            return;
        }
        if (this.activeKey == '15') {
            // ETF指令  需先点击计算才能试算
            if (!this.stockTableCalcState) {
                this.yh_message_warn('请先计算！');
                return;
            }
        }
        instruction.requestId = UUID() + '-' + new Date().getTime();
        instruction.instType = this.activeKey;
        instruction.directMode = this.directMode;

        // let stockInfo = this.stockInfo || {};

        let verInt = await this.verifyInstructionParam(instruction, stockInfo);
        if (!verInt) {
            return;
        }

        instruction.correspondingIndex = this.correspondingIndex;
        instruction = this.createInstruction(instruction, stockInfo);
        await this.getOpponentCode(instruction.opponentCode);
        let opponentName = '';
        this.opponentCodeSelectData.forEach(ele => {
            if (ele.dictKey === instruction.opponentCode) {
                opponentName = ele.dictKeyName;
            }
        });

        this.instDataSource.push({
            key: instruction.requestId,
            correspondingIndex: this.correspondingIndex,
            requestId: instruction.requestId,
            instType: instruction.instType,
            fundCode: instruction.fundCode,
            fundNameSt: instruction.fundNameSt,
            fundAccountCode: instruction.fundAccountCode,
            fundAccountName: instruction.fundAccountName,
            assetCode: instruction.assetCode,
            assetName: instruction.assetName,
            stockCode: stockInfo.stockCode,
            stockNameSt: stockInfo.stockNameSt || instruction.stockName,
            marketCode: instruction.marketCode,
            orderDirection: instruction.orderDirection,
            orderPriceType: instruction.orderPriceType,
            curName: stockInfo.curName,
            orderPrice: instruction.orderPrice,
            orderAmount: instruction.orderAmount,
            orderBalance: instruction.orderBalance,
            orderBalances: instruction.orderBalances, // 合约价值
            earnestBalance: instruction.earnestBalance,
            depositRate: instruction.depositRate,
            mutureDate: instruction.mutureDate,
            depositType: instruction.depositType,
            noticeDays: instruction.noticeDays,
            instructionType: instruction.instructionType,
            instructionTypeName: instruction.instructionTypeName,
            opponentCode: instruction.opponentCode,
            opponentName: opponentName,
            winningRate: instruction.winningRate,
            exchangeType: instruction.exchangeType,
            investType: instruction.investType,
            deadline: instruction.deadline,
            rate: instruction.rate,
            clearSpeed: instruction.clearSpeed,
            fullPrice: instruction.fullPrice,
            stockFaceBalance: instruction.stockFaceBalance,
            firstSettleDate: instruction.firstSettleDate, // 结算日期
            endSettleDate: instruction.endSettleDate,
            orderRate: instruction.orderRate,
            advanceLimitFlag: instruction.advanceLimitFlag,
            depositStartDate: instruction.depositStartDate,
            startDate: instruction.startDate,
            selectedPledgePOList: this.selectedList,
            // 基金转换相关字段
            destSecurityCode: instruction.destSecurityCode,
            destSecurityName: instruction.destSecurityName,
            destCombiId: instruction.destCombiId,
            destCombiName: instruction.destCombiName,
            bulkType: instruction.bulkType,
            // 一级债相关字段
            subject: instruction.subject,
            listDate: instruction.listDate,
            payDate: instruction.payDate,
            tenderWay: instruction.tenderWay,

            // 存款支取
            receiptNo: instruction.receiptNo,
            drawInterest: instruction.drawInterest,
            drawDate: instruction.drawDate, // 支取日期
            businessType: instruction.businessType, // 业务类型
            advanceType: instruction.advanceType, // 支取类型

            // 上交所固收
            yield: instruction.yield, // 到期收益率
            fullBalance: instruction.fullBalance,
            totalInterest: instruction.totalInterest, // 总应计利息
            targetType: instruction.targetType, // 目标类型
            // ETF
            directMode: instruction.directMode,
            etfStockListInfoDTOList: this.stockTableData,
            execType: stockInfo.execType,

            // 转融通
            strategyPlacing: instruction.strategyPlacing, // 限售出借
            originDealNo: instruction.originDealNo, // 合约编号
        });

        // this.$set(this.instTableMsg.returnData, 'data', this.instDataSource);
        // this.instTableMsg.returnData.data = JSON.parse(JSON.stringify(this.instDataSource));

        this.listKey++;
        instruction.selectedPledgePOList = this.selectedList;

        this.orginalData.push({ instruction: instruction, stockInfo: this.stockInfoCache[this.activeKey] });
        this.correspondingIndex = this.correspondingIndex + 1;
        // this.selectedRowKeys.push(instruction.requestId);

        this.renderCount[this.activeKey] += 1;

        if (this.activeKey == '5') {
            this.instructionCache[this.activeKey] = {
                orderDirection: this.instructionCache[this.activeKey].orderDirection,
            };
        } else {
            this.instructionCache[this.activeKey] = null;
        }

        this.stockInfoCache[this.activeKey] = null;

        this.selectedRowKeys = [];
        // 清空质押券相关
        this.pledgePositionsListMsg.returnData.data = [];
        this.pledgePositionsListMsg.returnData.total = 0;
        this.selectedList = [];
    }

    // 风险试算列表数据选中事件
    handleSelectionChange(checkedData: any) {}

    // 修改指令
    async handleUpdate() {
        if (this.activeKey == '4') {
            this.instructionCache[this.activeKey].selectedPledgePOList = this.selectedList;
        }
        if (this.activeKey == '15') {
            // ETF指令  需先点击计算才能试算
            if (!this.stockTableCalcState) {
                this.yh_message_warn('请先计算！');
                return;
            }
        }
        let instruction = JSON.parse(JSON.stringify(this.instructionCache[this.activeKey] || {}));
        let stockInfo = JSON.parse(JSON.stringify(this.stockInfoCache[this.activeKey] || {}));
        let fund = this.fundCodeSelectData.find(item => item.fundCode === String(instruction.fundCode)) || {};
        instruction['requestId'] = UUID() + '-' + new Date().getTime();
        instruction.instType = this.activeKey;

        let verInt = await this.verifyInstructionParam(instruction, stockInfo);
        if (!verInt) {
            return;
        }

        this.instructionCache[this.activeKey] = this.createInstruction(instruction, stockInfo);
        await this.getOpponentCode(instruction.opponentCode);
        let opponentName = '';
        this.opponentCodeSelectData.forEach(ele => {
            if (ele.dictKey === instruction.opponentCode) {
                opponentName = ele.dictKeyName;
            }
        });
        let tnuic = this.updateInstruction.instruction.correspondingIndex;
        let indexc = 0;
        for (let i = 0; i < this.instDataSource.length; i++) {
            if (this.instDataSource[i].correspondingIndex === tnuic) {
                indexc = i;
                break;
            }
        }
        this.instDataSource[indexc] = {
            key: instruction.requestId,
            correspondingIndex: tnuic,
            requestId: instruction.requestId,
            instType: instruction.instType,
            fundCode: instruction.fundCode,
            fundNameSt: fund.fundNameSt,
            fundAccountCode: instruction.fundAccountCode,
            fundAccountName: instruction.fundAccountName,
            assetCode: instruction.assetCode,
            assetName: instruction.assetName,
            stockCode: stockInfo.stockCode,
            stockNameSt: stockInfo.stockNameSt || instruction.stockName,
            marketCode: instruction.marketCode,
            orderDirection: instruction.orderDirection,
            orderPriceType: instruction.orderPriceType,
            curName: stockInfo.curName,
            orderPrice: instruction.orderPrice,
            orderAmount: instruction.orderAmount,
            orderBalance: instruction.orderBalance,
            orderBalances: instruction.orderBalances, // 合约价值
            earnestBalance: instruction.earnestBalance,
            depositRate: instruction.depositRate,
            mutureDate: instruction.mutureDate,
            depositType: instruction.depositType,
            noticeDays: instruction.noticeDays,
            instructionType: instruction.instructionType,
            instructionTypeName: instruction.instructionTypeName,
            opponentCode: instruction.opponentCode,
            opponentName: opponentName,
            winningRate: instruction.winningRate,
            exchangeType: instruction.exchangeType,
            investType: instruction.investType,
            deadline: instruction.deadline,
            rate: instruction.rate,
            clearSpeed: instruction.clearSpeed,
            fullPrice: instruction.fullPrice,
            stockFaceBalance: instruction.stockFaceBalance,
            firstSettleDate: instruction.firstSettleDate,
            endSettleDate: instruction.endSettleDate,
            orderRate: instruction.orderRate,
            advanceLimitFlag: instruction.advanceLimitFlag,
            depositStartDate: instruction.depositStartDate,
            startDate: instruction.startDate,
            selectedPledgePOList: instruction.selectedPledgePOList,
            // 基金转换相关字段
            destSecurityCode: instruction.destSecurityCode,
            destSecurityName: instruction.destSecurityName,
            destCombiId: instruction.destCombiId,
            destCombiName: instruction.destCombiName,
            bulkType: instruction.bulkType,
            // 一级债相关字段
            subject: instruction.subject,
            listDate: instruction.listDate,
            payDate: instruction.payDate,
            tenderWay: instruction.tenderWay,

            // 存款支取
            receiptNo: instruction.receiptNo,
            drawInterest: instruction.drawInterest,
            drawDate: instruction.drawDate, // 支取日期
            businessType: instruction.businessType, // 业务类型
            advanceType: instruction.advanceType, // 支取类型

            // 上交所固收
            yield: instruction.yield, // 到期收益率
            fullBalance: instruction.fullBalance,
            totalInterest: instruction.totalInterest, // 总应计利息
            targetType: instruction.targetType, // 目标类型
            // ETF
            directMode: instruction.directMode,
            etfStockListInfoDTOList: this.stockTableData,
            execType: stockInfo.execType,

            // 转融通
            strategyPlacing: instruction.strategyPlacing, // 限售出借
            originDealNo: instruction.originDealNo, // 合约编号
        };
        this.$set(this.instTableMsg.returnData, 'data', this.instDataSource);

        // this.instTableMsg.returnData.data = JSON.parse(JSON.stringify(this.instDataSource));

        this.orginalData[indexc].instruction = JSON.parse(JSON.stringify(this.instructionCache[this.activeKey]));
        this.orginalData[indexc].instruction.requestId = instruction.requestId;
        if (this.activeKey == '4') {
            this.orginalData[indexc].instruction.selectedPledgePOList = instruction.selectedPledgePOList;
        }
        this.orginalData[indexc].instruction.correspondingIndex = tnuic;
        this.orginalData[indexc].stockInfo = JSON.parse(JSON.stringify(this.stockInfoCache[this.activeKey]));
        this.listKey++;

        // this.selectedRowKeys.push(instruction.requestId);
        this.renderCount[this.activeKey] += 1;
        if (this.activeKey == '5') {
            this.instructionCache[this.activeKey] = {
                orderDirection: this.instructionCache[this.activeKey].orderDirection,
            };
        } else {
            this.instructionCache[this.activeKey] = null;
        }
        this.stockInfoCache[this.activeKey] = null;
        this.showType = true;
        this.selectedRowKeys = [];

        // 清空质押券相关
        this.pledgePositionsListMsg.returnData.data = [];
        this.pledgePositionsListMsg.returnData.total = 0;
        this.selectedList = [];
    }

    // 回显选中指令
    handleShowEdit(record: any) {
        // debugger
        this.renderCount[record.instType] += 1;
        let tno = this.orginalData.find(item => item.instruction.correspondingIndex === record.correspondingIndex);
        console.log(tno.instruction, 'lllllllllll');

        // 赋值
        this.instructionCache[record.instType] = JSON.parse(JSON.stringify(tno.instruction || {}));
        this.stockInfoCache[record.instType] = JSON.parse(JSON.stringify(tno.stockInfo || {}));
        this.updateInstruction = JSON.parse(JSON.stringify(tno || {}));
        this.activeKey = record.instType;
        this.showType = false;
        this.instructionCache[record.instType].stockCode = record.stockCode;

        if (record.instType === '4' && this.instructionCache[record.instType].selectedPledgePOList) {
            this.selectedList = this.instructionCache[record.instType].selectedPledgePOList;
            this.handlePledgeList();
        } else {
            this.selectedList = [];
        }
    }

    // 删除风险试算列表中的数据
    handleDelete(record: any) {
        let orginalData = this.orginalData;
        let indexc = 0;
        for (let i = 0; i < this.instDataSource.length; i++) {
            if (this.instDataSource[i].correspondingIndex === record.correspondingIndex) {
                indexc = i;
                break;
            }
        }
        this.instDataSource.splice(indexc, 1);
        this.$set(this.instTableMsg.returnData, 'data', this.instDataSource);

        this.instTableMsg.returnData.data = JSON.parse(JSON.stringify(this.instDataSource));
        this.orginalData.splice(indexc, 1);
        this.showType = true;
    }

    async getBatchMarketPrice(stockCodeArr: any) {
        await this.$axios
            .post('/dataEngine/getStockPriceBatch', stockCodeArr)
            .then((res: any) => {
                this.marketPriceArr = res;
            })
            .catch(() => {
                this.marketPriceArr = [];
            });
    }

    // 刷新风险试算列表 type: 1-手动刷新，2-点击试算时刷新
    async handleRefresh(type: string) {
        if (!this.instDataSource.length) {
            return;
        }
        let stockCodeArr = [];
        this.instDataSource.forEach(ele => {
            if (ele.instType === '6') {
                stockCodeArr.push(ele.stockCode);
            }
        });
        stockCodeArr = Array.from(new Set(stockCodeArr));
        await this.getBatchMarketPrice(stockCodeArr);
        if (type == '1') {
            this.yh_message_success('“当前市价”已刷新！');
        }
        const pojo = {};
        for (let i = 0; i < this.marketPriceArr.length; i++) {
            // pojo[this.marketPriceArr[i]['stockCode']] = '22';
            pojo[this.marketPriceArr[i]['stockCode']] = this.marketPriceArr[i]['stockPrice'];
        }
        this.instDataSource.forEach((ele, index) => {
            if (ele.orderPriceType == '2') {
                ele.orderPrice = pojo[ele.stockCode];
                if (ele.targetType == '1') {
                    ele.orderBalance = ele.orderPrice * ele.orderAmount;
                } else if (ele.targetType == '2') {
                    ele.orderAmount = ele.orderBalance / ele.orderPrice;
                }
            }
        });

        this.orginalData.forEach((ele, index) => {
            if (ele.instruction.orderPriceType == '2') {
                ele.instruction.orderPrice = pojo[ele.instruction.stockCode];
                if (ele.instruction.targetType == '1') {
                    ele.instruction.orderBalance = ele.instruction.orderPrice * ele.instruction.orderAmount;
                } else if (ele.instruction.targetType == '2') {
                    ele.instruction.orderAmount = ele.instruction.orderBalance / ele.instruction.orderPrice;
                }
            }
        });
    }

    /* ****************************** 风险试算列表end ************************ */

    /* *************************** 导出start ************************** */

    // 导出指令
    handleExport() {
        let datas = [];
        let pledgeDatas = [];
        let etfStockList = []; // 成分股信息
        let risk = new RiskCalculateImport();
        let columnName = risk.importColumnsInst;

        let fileName = '风险试算列表.xlsx';
        for (let i = 0; i < this.orginalData.length; i++) {
            let item = this.orginalData[i];
            let transformedColumn = this.transformExport(item.instruction, item.stockInfo || {});
            datas.push(transformedColumn);

            // 导出质押券数据(银行间回购)
            let selectedPledgePOList = item.instruction.selectedPledgePOList || [];
            selectedPledgePOList.forEach(ele => {
                this.$set(ele, 'instNo', item.instruction.requestId);
            });
            pledgeDatas = pledgeDatas.concat(selectedPledgePOList);

            // 导出成分股数据(etf)
            let etfStockListInfoDTOList = item.instruction.etfStockListInfoDTOList || [];
            etfStockListInfoDTOList.forEach(ele => {
                ele.fundCode = item.instruction.fundCode + '/' + item.instruction.fundNameSt;
                ele.assetCode = item.instruction.assetCode + '/' + item.instruction.assetName;
                ele.fundAccountCode = item.instruction.fundAccountCode + '/' + item.instruction.fundAccountCode;
                this.$set(ele, 'associationNo', item.instruction.requestId);
            });
            let summary: any = {
                associationNo: '关联编号' + item.instruction.requestId + '总计',
                stockCode: etfStockListInfoDTOList.length + '只',
                marketValue: 0,
                redeemBalance: 0,
                purchaseBalance: 0,
            };
            etfStockListInfoDTOList.forEach(ele => {
                summary.marketValue += ele.marketValue; // 市值汇总
                summary.redeemBalance += ele.redeemBalance; // 赎回替代金额汇总
                summary.purchaseBalance += ele.purchaseBalance; // 申购金额替代汇总
            });
            etfStockListInfoDTOList.push(summary);
            etfStockList = etfStockList.concat(etfStockListInfoDTOList);
        }
        let sheetNames = ['风险试算列表', '质押券', 'ETF成分股信息'];
        exportExcels([columnName, risk.importPledgeColumns, risk.importETFColumns], [datas, pledgeDatas, etfStockList], fileName, sheetNames);
    }

    // 导出指令为excel模板 转化过程(确定导出字段
    transformExport(instruction, stockInfo) {
        let exportColumns: any = {};

        exportColumns.fundCode = instruction.fundCode;
        exportColumns.fundAccountCode = instruction.fundAccountCode;
        exportColumns.assetCode = instruction.assetCode;
        let insttype = instruction.instType;
        exportColumns.instType = this.instTypeMap[insttype];
        // 导出证券编码和市场
        exportColumns.stockCode = stockInfo.stockCode;
        exportColumns.reportCode = instruction.reportCode;
        exportColumns.orderDirection = this.OrderDirection[instruction.orderDirection];
        exportColumns.orderAmount = instruction.orderAmount;
        exportColumns.investType = this.Invest.investType[instruction.investType];

        if (insttype === '6' || insttype == '14') {
            exportColumns.instructionTypeName = instruction.businessType;
        }
        if (instruction.instructionTypeName) {
            instruction.instructionTypeName = this.AllBusinessTypeMap[instruction.instructionTypeName]
                ? this.AllBusinessTypeMap[instruction.instructionTypeName]
                : instruction.instructionTypeName;
        }
        if (instruction.clearSpeed) {
            instruction.clearSpeed = this.clearSpeedType[instruction.clearSpeed]
                ? this.clearSpeedType[instruction.clearSpeed]
                : instruction.clearSpeed;
        }
        if (instruction.depositType) {
            instruction.depositType = this.DepositType[instruction.depositType] ? this.DepositType[instruction.depositType] : instruction.depositType;
        }
        if (instruction.advanceLimitFlag) {
            instruction.advanceLimitFlag = this.Invest.advanceLimitFlagType[instruction.advanceLimitFlag]
                ? this.Invest.advanceLimitFlagType[instruction.advanceLimitFlag]
                : instruction.advanceLimitFlag;
        }
        exportColumns.instructionTypeName = instruction.instructionTypeName;
        exportColumns.opponentCode = instruction.opponentCode;

        if (insttype === '1') {
            exportColumns.orderPrice = instruction.netPrice;
        } else if (insttype === '2') {
            exportColumns.orderAmount = Number(instruction.stockFaceBalance) / Number(stockInfo.facePrice);
            exportColumns.clearSpeed = instruction.clearSpeed;
            exportColumns.firstSettleDate = instruction.firstSettleDate;
            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.fullPrice = instruction.fullPrice;
            exportColumns.stockFaceBalance = instruction.stockFaceBalance;
        } else if (insttype === '3') {
            exportColumns.orderPrice = instruction.orderRate;
        } else if (insttype === '4') {
            exportColumns.clearSpeed = instruction.clearSpeed;
            exportColumns.startDate = instruction.firstSettleDate;
            exportColumns.mutureDate = instruction.endSettleDate;
            exportColumns.orderPrice = instruction.orderRate;
            exportColumns.orderAmount = instruction.orderBalance;
            exportColumns.repoDay = instruction.repoDay;
            exportColumns.firstSettleDate = instruction.firstSettleDate;
            exportColumns.endSettleDate = instruction.endSettleDate;
            exportColumns.orderRate = instruction.orderRate;
            exportColumns.orderBalance = instruction.orderBalance;
        } else if (insttype === '5') {
            exportColumns.stockCode = instruction.bankCode;
            exportColumns.depositType = instruction.depositType;
            exportColumns.noticeDays = instruction.noticeDays;
            // exportColumns.orderAmount = instruction.orderBalance;
            exportColumns.orderPrice = instruction.depositRate;
            exportColumns.startDate = instruction.depositStartDate;
            exportColumns.mutureDate = instruction.mutureDate;
            exportColumns.advanceLimitFlag = instruction.advanceLimitFlag;
            exportColumns.endSettleDate = instruction.endSettleDate;
            exportColumns.orderBalance = instruction.orderBalance;
            exportColumns.depositRate = instruction.depositRate;
            //
            exportColumns.drawDate = instruction.drawDate;
            exportColumns.receiptNo = instruction.receiptNo;
            exportColumns.drawInterest = instruction.drawInterest;
            exportColumns.advanceType = instruction.advanceType;
        } else if (insttype === '6' || insttype == '11') {
            if (instruction.showType == '2') {
                exportColumns.deadline = instruction.deadline;
                exportColumns.rate = instruction.rate;
            } else if (instruction.showType == 3) {
                if (stockInfo.quoteType === '1') {
                    exportColumns.orderPrice = instruction.netPrice;
                    exportColumns.orderBalance = instruction.netMoney;
                } else {
                    exportColumns.orderPrice = instruction.allPrice;
                    exportColumns.orderBalance = instruction.allMoney;
                }
            } else if (instruction.showType == 8) {
                exportColumns.fullPrice = instruction.fullPrice;
                exportColumns.fullBalance = instruction.fullBalance;
                exportColumns.yield = instruction.yield;
                exportColumns.totalInterest = instruction.totalInterest;
            }

            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.orderBalance = instruction.orderBalance;
            if (insttype === '6') {
                exportColumns.exchangeType = this.exchangeTypeMap[instruction.showType];
            }
            exportColumns.winningRate = instruction.winningRate;
            exportColumns.orderRate = instruction.orderRate;
        } else if (insttype === '7') {
            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.orderBalance = instruction.orderBalances;
            // exportColumns.orderBalance = instruction.orderBalance;
        } else if (insttype === '8') {
            exportColumns.destCombiId = instruction.destCombiId;
            exportColumns.destCombiName = instruction.destCombiName;
            exportColumns.destSecurityCode = instruction.destSecurityCode;
            exportColumns.destSecurityName = instruction.destSecurityName;
            exportColumns.bulkType = this.Invest.bulkType[instruction.bulkType] || instruction.bulkType;
            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.orderBalance = instruction.orderBalance;
        } else if (insttype === '9') {
            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.orderBalance = instruction.orderBalance;
            exportColumns.earnestBalance = instruction.earnestBalance;
        } else if (insttype === '10') {
            exportColumns.orderPrice = instruction.orderPrice;
            exportColumns.orderBalance = instruction.orderBalance;
            exportColumns.subject = this.Invest.bidSubjectType[instruction.subject];
            exportColumns.tenderWay = this.Invest.tenderWayType[instruction.tenderWay];
            exportColumns.listDate = instruction.listDate;
            exportColumns.payDate = instruction.payDate;
        } else if (insttype == '14') {
            exportColumns.deadline = instruction.deadline;
            exportColumns.rate = instruction.rate;
        } else if (insttype == '15') {
            exportColumns.orderBalance = instruction.orderBalance;
        } else if (insttype == '20') {
            exportColumns.orderBalance = instruction.orderBalance;
        }
        exportColumns.instNo = instruction.requestId;
        return exportColumns;
    }

    /* *************************** 导出end ************************** */

    /* ************************** 导入start ************************* */

    // 获取证券信息
    getStockReportSelectAsync(type: number, data: any) {
        let res = new Promise((resolve, reject) => {
            this.$axios
                .post('/dict/stock/report/select/' + type, data)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        return res;
    }

    // 获取可申购证券信息
    getUnderNetStockList(data: any) {
        let res = new Promise((resolve, reject) => {
            this.$axios
                .post('/position/stock/offlineSubs', data)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        return res;
    }

    // 获取可转出证券信息
    getOutStockCodeList(data: any) {
        let res = new Promise((resolve, reject) => {
            this.$axios
                .post('/position/convertibleStock/out', data)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        return res;
    }

    // 债券一级投标获取证券信息
    getPrimaryBondInfo(data: any) {
        let res = new Promise((resolve, reject) => {
            this.$axios
                .post('/dict/bond/select', data)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        return res;
    }

    closeImportDialog() {
        this.importDialog = false;
    }

    // 校验(不可为空)
    verifyImportInfo(instruction) {
        console.log('verify:', instruction);

        let verify: any = {
            fundCode: '产品代码',
            fundAccountCode: '组合编码',
            instType: '指令类型',
            orderPrice: '指令价格',
            orderAmount: '指令数量',
            orderDirection: '委托方向',
            instructionTypeName: '业务类型',
        };
        if (instruction.instType === '7') {
            // 期货指令
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '合约代码',
                instType: '指令类型',
                orderPrice: '指令价格',
                orderAmount: '指令数量',
                orderDirection: '委托方向',
                investType: '投资类型',
            };
        } else if (instruction.instType === '2') {
            // 银行间债券
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                firstSettleDate: '结算日期',
                orderDirection: '订单方向',
                clearSpeed: '清算速度',
                orderPrice: '净价价格',
                stockFaceBalance: '券面总额',
            };
        } else if (instruction.instType === '4') {
            // 银行间回购
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                repoDay: '回购天数',
                orderDirection: '订单方向',
                clearSpeed: '清算速度',
                firstSettleDate: '结算日期',
                orderRate: '回购利率',
                orderBalance: '回购金额',
            };
        } else if (instruction.instType === '8') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                instructionTypeName: '业务类型',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
        } else if (instruction.instType === '5') {
            if (instruction.orderDirection == 'F') {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    depositType: '存款类型',
                    orderBalance: '存款金额',
                    depositRate: '存款利率',
                    startDate: '起息日',
                    advanceLimitFlag: '提前支取限制',
                };
                //  endSettleDate: '到期日期',
                // drawDate: '支取日期',
                // if (instruction.depositType == '2') {
                //     delete verify.endSettleDate;
                //     instruction.advanceType == '1' && delete verify.drawDate;
                // } else {
                //     delete verify.drawDate;
                // }
            } else if (instruction.oderDirection == 'i') {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    depositType: '存款类型',
                    orderBalance: '存款金额',
                    depositRate: '存款利率',
                    startDate: '起息日',
                    advanceLimitFlag: '提前支取限制',
                    drawDate: '支取日期',
                    receiptNo: '存单号',
                };
            }
            //  stockCode: '证券代码',
            //   endSettleDate: '到期日期',

            // if (instruction.depositType !== '2') {
            //     delete verify.depositType;
            // }
        } else if (instruction.instType === '6') {
            if (!instruction.exchangeType) {
                return '交易所债券指令确定交易所指令类型！';
            }
            if (instruction.exchangeType == 1) {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    stockCode: '证券代码',
                    orderDirection: '委托方向',
                    instructionTypeName: '业务类型',
                    orderPrice: '指令价格',
                    orderAmount: '指令数量',
                };
            } else if (instruction.exchangeType == 2) {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    stockCode: '证券代码',
                    orderDirection: '委托方向',
                    instructionTypeName: '业务类型',
                    deadline: '期限',
                    rate: '费率',
                    orderAmount: '融出数量',
                };
            } else if (instruction.exchangeType == 3 || instruction.exchangeType == 4 || instruction.exchangeType == 5) {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    stockCode: '证券代码',
                    orderDirection: '委托方向',
                    instructionTypeName: '业务类型',
                    orderPrice: '指令价格',
                    orderAmount: '指令数量',
                };
            } else if (instruction.exchangeType == 6) {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    stockCode: '证券代码',
                    orderDirection: '委托方向',
                    instructionTypeName: '业务类型',
                    orderRate: '回购利率',
                    orderBalance: '指令金额',
                };
            }
        } else if (instruction.instType === '20') {
            verify = {
                fundCode: '产品代码',
                stockCode: '证券代码',
                orderBalance: '指令数量',
            };
        }
        if (instruction.instType === '7' || instruction.instType === '8') {
            // verify.businessType = '业务类型'
            delete verify.instructionTypeName;
        }
        if (instruction.instType === '8') {
            if (instruction.orderDirection === 'D' || instruction.orderDirection === 'p') {
                delete verify.orderAmount;
            } else if (instruction.orderDirection === 'q') {
                delete verify.orderBalance;
            }
            delete verify.orderPrice;
        } else if (instruction.instType === '9') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                orderPrice: '申购价格',
                orderAmount: '申购数量',
                orderBalance: '申购金额',
                opponentCode: '交易对手',
                earnestBalance: '申购定金',
            };

            if (instruction.orderAmount !== '' || instruction.orderAmount !== undefined) {
                if (instruction.orderAmount === '0.00') {
                    this.yh_message_warn('申购数量不能为0！');
                    return false;
                } else if (Number(instruction.orderAmount) > 999999999999.0) {
                    this.yh_message_warn('申购数量不能超过999999999999.00！');
                    return false;
                }
            }
        } else if (instruction.instType === '10') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                // payDate: '缴款日期',
                // listDate: '上市日期',
                orderPrice: '价格',
                orderBalance: '投标金额',
            };
        } else if (instruction.instType == '14') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                instructionTypeName: '业务类型',
                deadline: '期限',
                rate: '费率',
                orderAmount: '融出数量',
            };
        } else if (instruction.instType === '15') {
            // ETF指令
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
        }
        // todo  券商模式需要判断assetCode是否可为空？
        for (let key in verify) {
            if (!instruction[key]) {
                return verify[key] + ' 不可为空';
            }
        }

        if (!['8', '14', '15', '20'].includes(instruction.instType)) {
            if (isNaN(instruction.orderPrice) || isNaN(instruction.orderAmount)) {
                return '指令价格或指令数量输入错误';
            }
        }

        let insttype = String(instruction.instType);
        let orderDirection = String(instruction.orderDirection);

        if (insttype === '1') {
            if (orderDirection !== '3' && orderDirection !== '4') return "债券指令的委托方向只能为'3'或'4'";
        } else if (insttype === '2') {
            // if (orderDirection !== '3' && orderDirection !== '4') return "债券指令的委托方向只能为'3'或'4'";
            if (String(instruction.clearSpeed) !== '0' && String(instruction.clearSpeed) !== '1') return "清算速度只能为'0'或'1'";
        } else if (insttype === '3') {
            if (orderDirection !== '5' && orderDirection !== '6') return "回购指令的委托方向只能为'5'或'6'";
        } else if (insttype === '4') {
            if (orderDirection !== '5' && orderDirection !== '6') return "回购指令的委托方向只能为'5'或'6'";
            if (String(instruction.clearSpeed) !== '0' && String(instruction.clearSpeed) !== '1') return "清算速度只能为'0'或'1'";
            if (!instruction.repoDay || isNaN(instruction.repoDay)) return '回购天数不能为空';
        } else if (insttype === '5') {
            // if (orderDirection !== 'F') return "存款的委托方向只能为'F'";
            let deposittype = String(instruction.depositType);
            if (deposittype !== '1' && deposittype !== '2' && deposittype !== '3') return '存款类型有误';
            if (deposittype === '2' && (!instruction.noticeDays || isNaN(instruction.noticeDays))) return '通知存款请输入通知天数。';
            let flag = String(instruction.advanceLimitFlag);
            if (flag !== '1' && flag !== '2' && flag !== '3' && flag !== '4') return "支取类型只能为'1''2''3''4'";
        }

        return true;
    }

    /**
     * 批量导入 为引擎转化指令信息
     */
    async transformImport(instruction) {
        // 校验产品信息
        let fund = this.fundCodeSelectData.find(item => item.fundCode === String(instruction.fundCode)) || {};
        if (Object.keys(fund).length == 0) {
            fund = this.fundCodeSelectData.find(item => item.fundNameSt === String(instruction.fundCode)) || {};
        }
        let fundAccount =
            (this.fundAccountCodeSelectData[fund.fundCode] || []).find(item => item.fundAccountCode === String(instruction.fundAccountCode)) || {};
        if ((!fund.fundCode || !fundAccount.fundAccountName) && String(instruction.instType) !== '20') {
            return '错误的产品代码或组合代码。';
        }
        if (!instruction.stockCode && String(instruction.instType) !== '4') {
            return '证券代码不能为空';
        }

        let insttype = String(instruction.instType);
        if (insttype === '2') {
            // 银行间债券
            let bankzq: any = new BankZQ();
            let res = await this.getStockReportSelectAsync(3, {
                dictKey: String(instruction.stockCode),
                dictKeyName: '',
            });
            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // let tradedays = getSystemTradeDayAsync();
            bankzq.tradeDays = this.tradeDays.map(item => Number(item)).sort((a, b) => a - b);

            // eslint-disable-next-line camelcase
            let bankzq_ins = JSON.parse(JSON.stringify(bankzq.instruction));
            bankzq_ins.correspondingIndex = this.correspondingIndex++;
            bankzq_ins.instType = insttype;
            bankzq_ins.reportCode = stockInfo.reportCode;
            // bankzq_ins.reportCode = String(instruction.reportCode);
            bankzq_ins.stockCode = String(instruction.stockCode);
            bankzq_ins.fundNameSt = String(fund.fundNameSt);
            bankzq_ins.fundCode = fund.fundCode;
            bankzq_ins.fundAccountCode = String(instruction.fundAccountCode);
            bankzq_ins.fundAccountName = fundAccount.fundAccountName;
            bankzq_ins.assetCode = fundAccount.assetCode;
            bankzq_ins.assetName = fundAccount.assetName;
            bankzq_ins.clearSpeed = String(instruction.clearSpeed);
            bankzq_ins.fullPrice = instruction.fullPrice;
            bankzq_ins.stockFaceBalance = instruction.stockFaceBalance;

            let firstSettleDate = instruction.firstSettleDate;
            if (firstSettleDate && !isNaN(firstSettleDate)) {
                bankzq_ins.firstSettleDate = String(firstSettleDate);
            } else {
                if (bankzq_ins.clearSpeed === '0') {
                    bankzq_ins.firstSettleDate = moment().format('YYYYMMDD');
                } else {
                    bankzq_ins.firstSettleDate = bankzq.name.tradeDays.find(item => item > Number(moment().format('YYYYMMDD')));
                }
            }

            bankzq_ins.orderPrice = String(instruction.orderPrice);
            bankzq_ins.orderDirection = String(instruction.orderDirection);
            bankzq_ins.fullPrice = bankzq.calcFullPrice(bankzq_ins, stockInfo);
            bankzq_ins.totalInterest = String(instruction.orderAmount * stockInfo.tDayInterest);
            bankzq_ins.orderBalance = instruction.orderPrice * instruction.orderAmount;
            bankzq_ins.settlementBalance = Number(bankzq_ins.totalInterest) + Number(bankzq_ins.orderBalance);
            bankzq_ins.stockFaceBalance = instruction.orderAmount * stockInfo.facePrice;
            bankzq_ins.opponentCode = instruction.opponentCode;
            bankzq_ins.investType = instruction.investType;
            bankzq_ins.businessType = instruction.instructionTypeName;

            this.createInstruction(bankzq_ins, stockInfo);
            let item = { instruction: bankzq_ins, stockInfo: stockInfo };
            return item;
        } else if (insttype === '4') {
            // 银行间回购

            let repoDay = instruction.repoDay;
            let bankhg: any = new BankHG();
            // let tradedays = getSystemTradeDayAsync();
            bankhg.tradeDays = this.tradeDays.map(item => Number(item)).sort((a, b) => a - b);

            let stockInfo = bankhg.stockInfo;
            stockInfo.stockCode = 'R' + PrefixInteger(Number(repoDay || 0), 3) + ' YH';
            stockInfo.reportCode = 'R' + PrefixInteger(Number(repoDay || 0), 3);
            stockInfo.stockNameSt = repoDay + ' 天回购';
            stockInfo.marketCode = '5';
            stockInfo.curCode = 'CNY';
            stockInfo.curName = '人民币';

            // eslint-disable-next-line camelcase
            let bankhg_ins = JSON.parse(JSON.stringify(bankhg.instruction));
            bankhg_ins.correspondingIndex = this.correspondingIndex++;
            bankhg_ins.instType = insttype;
            bankhg_ins.instNo = instruction.instNo;
            bankhg_ins.fundCode = fund.fundCode;
            bankhg_ins.fundAccountCode = String(instruction.fundAccountCode);
            bankhg_ins.fundNameSt = String(fund.fundNameSt);
            bankhg_ins.fundAccountName = fundAccount.fundAccountName;
            bankhg_ins.assetCode = fundAccount.assetCode;
            bankhg_ins.assetName = fundAccount.assetName;
            bankhg_ins.clearSpeed = String(instruction.clearSpeed);
            bankhg_ins.repoDay = repoDay;
            bankhg_ins.orderRate = instruction.orderPrice;
            bankhg_ins.orderDirection = String(instruction.orderDirection);
            bankhg_ins.orderBalance = instruction.orderAmount;
            bankhg_ins.orderRate = instruction.orderRate;
            bankhg_ins.investType = instruction.investType;
            let firstSettleDate = instruction.firstSettleDate;
            if (firstSettleDate && !isNaN(firstSettleDate)) {
                bankhg_ins.firstSettleDate = String(firstSettleDate);
            } else {
                bankhg_ins.firstSettleDate = bankhg.calcFirstSettleDate(bankhg_ins);
            }
            let endSettleDate = instruction.endSettleDate;
            if (endSettleDate && !isNaN(endSettleDate)) {
                bankhg_ins.endSettleDate = String(endSettleDate);
            } else {
                bankhg_ins.endSettleDate = bankhg.calcEndSettleDate(bankhg_ins);
            }
            bankhg_ins.factUseMoney = bankhg.calcFactUseMoney(bankhg_ins);
            bankhg_ins.shouldInterest = bankhg.calcShouldInterest(bankhg_ins);
            bankhg_ins.expirePayBalance = bankhg.calcExpirePayBalance(bankhg_ins);
            bankhg_ins.opponentCode = instruction.opponentCode;

            this.createInstruction(bankhg_ins, stockInfo);
            let item = { instruction: bankhg_ins, stockInfo: stockInfo };
            return item;
        } else if (insttype === '5') {
            let reportCode = { '1': '870870', '2': '860860', '3': '890890', '6': '880880' }[String(instruction.depositType)];
            let res: any = await this.getStockReportSelectAsync(-1, {
                dictKey: reportCode,
                dictKeyName: '',
            });
            let stockInfo = res[0];
            if (res && res.length > 0) {
                stockInfo = res.find(item => item && item.stockCode && item.stockCode === reportCode + ' CW');
            }
            if (!stockInfo) {
                return '错误的证券代码';
            }
            let ck = new CK();

            //  instruction.orderDirection == 'F' ? new CK() : new CkPaid()
            // eslint-disable-next-line camelcase
            let ck_ins: any = JSON.parse(JSON.stringify(ck.instruction));

            ck_ins.correspondingIndex = this.correspondingIndex++;
            ck_ins.orderDirection = instruction.orderDirection;
            ck_ins.instType = insttype;
            ck_ins.fundNameSt = String(fund.fundNameSt);
            ck_ins.fundCode = fund.fundCode;
            ck_ins.fundAccountName = fundAccount.fundAccountName;
            ck_ins.assetCode = fundAccount.assetCode;
            ck_ins.assetName = fundAccount.assetName;
            ck_ins.bankCode = String(instruction.stockCode);
            ck_ins.depositRate = instruction.orderPrice;
            ck_ins.fundAccountCode = String(instruction.fundAccountCode);

            let date = instruction.endSettleDate;
            if (instruction.orderDirection == 'F') {
                date = instruction.depositType == '2' ? instruction.drawDate : instruction.endSettleDate;
            } else if (instruction.orderDirection == 'i') {
                date = instruction.drawDate;
            }
            //
            if (!isNaN(instruction.startDate) && !isNaN(date)) {
                ck_ins.depositStartDate = String(instruction.startDate);
                ck_ins.mutureDate = String(date);
            } else {
                return '请输入正确的存款日期';
            }
            ck_ins.depositType = String(instruction.depositType);
            ck_ins.noticeDays = instruction.noticeDays;
            ck_ins.reportCode = String(instruction.reportCode);
            ck_ins.stockCode = stockInfo.reportCode;
            // ck_ins.stockCode = String(instruction.stockCode);
            ck_ins.orderBalance = instruction.orderBalance;
            ck_ins.advanceLimitFlag = String(instruction.advanceLimitFlag);
            ck_ins.drawDate = instruction.drawDate;

            ck_ins.depositInterest = ck.calcDepositInterest(ck_ins);
            ck_ins.expireBalance = ck.calcExpireBalance(ck_ins);

            ck_ins.opponentCode = instruction.opponentCode;
            if (ck_ins.instructionTypeName === '存款类') {
                ck_ins.businessType = 'B';
            }
            ck_ins.investType = instruction.investType;

            ck_ins.advanceType = instruction.advanceType;
            ck_ins.drawInterest = instruction.drawInterest;
            ck_ins.receiptNo = instruction.receiptNo;
            ck_ins.drawDate = instruction.drawDate;

            this.createInstruction(ck_ins, stockInfo);
            let item = { instruction: ck_ins, stockInfo: stockInfo };
            return item;
        } else if (insttype === '6' || insttype === '11') {
            // 交易所指令

            // 获取证券信息
            let res: any;
            if (insttype === '6') {
                res = await this.getStockReportSelectAsync(1, {
                    dictKey: String(instruction.stockCode),
                    dictKeyName: '',
                });
            } else {
                // 北交所
                res = await this.getStockReportSelectAsync(9, {
                    dictKey: String(instruction.stockCode),
                    dictKeyName: '',
                });
            }

            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let exchangeOrder: any = new ExchangeOrder();
            // eslint-disable-next-line camelcase
            let exchangeOrder_ins = JSON.parse(JSON.stringify(exchangeOrder.instruction));
            exchangeOrder_ins.correspondingIndex = this.correspondingIndex++;
            exchangeOrder_ins.instType = insttype;
            exchangeOrder_ins.fundCode = fund.fundCode;
            exchangeOrder_ins.reportCode = stockInfo.reportCode;
            exchangeOrder_ins.stockCode = String(instruction.stockCode);
            exchangeOrder_ins.fundNameSt = String(fund.fundNameSt);
            exchangeOrder_ins.fundAccountCode = String(instruction.fundAccountCode);
            exchangeOrder_ins.fundAccountName = fundAccount.fundAccountName;
            exchangeOrder_ins.assetCode = fundAccount.assetCode;
            exchangeOrder_ins.assetName = fundAccount.assetName;
            let importExchangeTypeMapping = DictionConstUtil.ReversePojo(this.exchangeTypeMap);
            exchangeOrder_ins.showType = importExchangeTypeMapping[instruction.exchangeType];
            exchangeOrder_ins.exchangeType = exchangeOrder_ins.showType;
            exchangeOrder_ins.orderAmount = instruction.orderAmount;
            exchangeOrder_ins.investType = instruction.investType;
            if (exchangeOrder_ins.showType == 3) {
                if (stockInfo.quoteType === '1') {
                    exchangeOrder_ins.netPrice = instruction.orderPrice;
                    exchangeOrder_ins.netMoney = instruction.orderBalance;
                } else {
                    exchangeOrder_ins.allPrice = instruction.orderPrice;
                    exchangeOrder_ins.allMoney = instruction.orderBalance;
                }
            } else if (exchangeOrder_ins.showType == 8) {
                exchangeOrder_ins.orderPrice = instruction.orderPrice;
                exchangeOrder_ins.fullPrice = instruction.fullPrice;
                exchangeOrder_ins.fullBalance = instruction.fullBalance;
                exchangeOrder_ins.yield = instruction.yield;
                exchangeOrder_ins.totalInterest = instruction.totalInterest;
                exchangeOrder_ins.opponentCode = instruction.opponentCode;
            } else {
                exchangeOrder_ins.orderPrice = instruction.orderPrice;
            }
            if (['1', '3', '4', '5'].includes(instruction.exchangeType)) {
                exchangeOrder_ins.orderBalance = Number(instruction.orderPrice || 0) * Number(instruction.orderAmount || 0);
            } else {
                exchangeOrder_ins.orderBalance = instruction.orderBalance;
                exchangeOrder_ins.orderRate = instruction.orderRate;
            }
            exchangeOrder_ins.orderAmount = String(instruction.orderAmount);
            exchangeOrder_ins.orderDirection = String(instruction.orderDirection);
            exchangeOrder_ins.targetType = '1';
            exchangeOrder_ins.orderPriceType = '1';
            exchangeOrder_ins.instructionTypeName = instruction.instructionTypeName;
            exchangeOrder_ins.winningRate = instruction.winningRate;
            exchangeOrder_ins.businessType = instruction.instructionTypeName;
            exchangeOrder_ins.deadline = instruction.deadline;
            exchangeOrder_ins.rate = instruction.rate;
            this.createInstruction(exchangeOrder_ins, stockInfo);
            let item = { instruction: exchangeOrder_ins, stockInfo: stockInfo };
            return item;
        } else if (insttype === '7') {
            // 获取证券信息
            let res = await this.getStockReportSelectAsync(2, {
                dictKey: String(instruction.stockCode),
                dictKeyName: '',
            });
            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let futuresOrder: any = new FuturesOrder();
            let futuresInstruction = JSON.parse(JSON.stringify(futuresOrder.instruction));
            futuresInstruction.correspondingIndex = this.correspondingIndex++;
            // futuresInstruction.reportCode = instruction.reportCode;
            futuresInstruction.reportCode = stockInfo.reportCode;
            futuresInstruction.stockCode = instruction.stockCode;
            futuresInstruction.fundCode = fund.fundCode;
            futuresInstruction.fundNameSt = String(fund.fundNameSt);
            futuresInstruction.fundAccountCode = String(instruction.fundAccountCode);
            futuresInstruction.fundAccountName = fundAccount.fundAccountName;
            futuresInstruction.assetCode = fundAccount.assetCode;
            futuresInstruction.assetName = fundAccount.assetName;
            futuresInstruction.orderDirection = String(instruction.orderDirection);
            futuresInstruction.instType = insttype;
            futuresInstruction.investType = instruction.investType;
            futuresInstruction.orderAmount = instruction.orderAmount;
            futuresInstruction.orderPrice = instruction.orderPrice;
            futuresInstruction.instructionTypeName = instruction.instructionTypeName;
            let contractMulti = await getFutureContractMulti(instruction.stockCode);
            if (!contractMulti) {
                contractMulti = 0;
            } else {
                this.contractMulti = contractMulti;
            }

            if (!instruction.orderBalance) {
                let contractMulti = futuresOrder.getContractMulti(instruction.stockCode);
                futuresInstruction.orderBalance =
                    Number(futuresInstruction.orderPrice || 0) * Number(futuresInstruction.orderAmount || 0) * Number(contractMulti || 0);
            } else {
                futuresInstruction.orderBalance = instruction.orderBalance;
            }
            futuresInstruction.orderBalances =
                Number(futuresInstruction.orderPrice || 0) * Number(futuresInstruction.orderAmount || 0) * Number(contractMulti || 0);

            // if (futuresInstruction.instructionTypeName === '期货业务') {
            //   futuresInstruction.businessType = '4'
            // }
            futuresInstruction.businessType = futuresInstruction.instructionTypeName;
            this.createInstruction(futuresInstruction, stockInfo);
            return { instruction: futuresInstruction, stockInfo: stockInfo };
        } else if (insttype === '8') {
            if (instruction.orderDirection !== 'E') {
                // 获取证券信息
                let res = await this.getStockReportSelectAsync(5, {
                    dictKey: String(instruction.stockCode),
                    dictKeyName: '',
                });
                let stockInfo = res[0];
                if (!stockInfo) {
                    return '错误的证券代码';
                }
                // 组装指令
                let overCounterFundOrder: any = new OverCounterFundOrder();
                let overCounterFundInstruction = JSON.parse(JSON.stringify(overCounterFundOrder.instruction));
                overCounterFundInstruction.correspondingIndex = this.correspondingIndex++;
                overCounterFundInstruction.fundCode = fund.fundCode;
                overCounterFundInstruction.fundNameSt = String(fund.fundNameSt);
                overCounterFundInstruction.fundAccountCode = String(instruction.fundAccountCode);
                overCounterFundInstruction.fundAccountName = fundAccount.fundAccountName;
                overCounterFundInstruction.assetCode = fundAccount.assetCode;
                overCounterFundInstruction.assetName = fundAccount.assetName;
                overCounterFundInstruction.orderDirection = String(instruction.orderDirection);
                overCounterFundInstruction.orderAmount = instruction.orderAmount;
                overCounterFundInstruction.orderBalance = instruction.orderBalance;
                overCounterFundInstruction.instType = insttype;
                overCounterFundInstruction.investType = instruction.investType;
                overCounterFundInstruction.reportCode = stockInfo.reportCode;
                overCounterFundInstruction.stockCode = instruction.stockCode;
                overCounterFundInstruction.businessType = instruction.instructionTypeName;

                this.createInstruction(overCounterFundInstruction, stockInfo);
                return { instruction: overCounterFundInstruction, stockInfo: stockInfo };
            } else {
                let reportCode = '';
                if (instruction.stockCode) {
                    reportCode = String(instruction.stockCode).split(' ')[0];
                }

                // 获取证券信息
                let res = await this.getStockReportSelectAsync(5, {
                    dictKey: String(instruction.stockCode),
                    dictKeyName: '',
                });
                let stockInfo = res[0];
                if (!stockInfo) {
                    return '错误的证券代码';
                }

                // 组装指令
                let fundTransferForm: any = new FundTransferForm();
                let fundTransferInstruction = JSON.parse(JSON.stringify(fundTransferForm.instruction));
                fundTransferInstruction.correspondingIndex = this.correspondingIndex++;
                fundTransferInstruction.fundCode = fund.fundCode;
                fundTransferInstruction.fundNameSt = String(fund.fundNameSt);
                fundTransferInstruction.fundAccountCode = String(instruction.fundAccountCode);
                fundTransferInstruction.fundAccountName = fundAccount.fundAccountName;
                fundTransferInstruction.assetCode = fundAccount.assetCode;
                fundTransferInstruction.assetName = fundAccount.assetName;
                fundTransferInstruction.orderDirection = String(instruction.orderDirection);
                fundTransferInstruction.orderPrice = instruction.orderPrice;
                fundTransferInstruction.orderAmount = instruction.orderAmount;
                fundTransferInstruction.orderBalance = instruction.orderBalance;
                fundTransferInstruction.instType = insttype;
                fundTransferInstruction.investType = instruction.investType;
                fundTransferInstruction.reportCode = reportCode;
                fundTransferInstruction.stockCode = instruction.stockCode;
                fundTransferInstruction.businessType = instruction.instructionTypeName;
                fundTransferInstruction.destSecurityCode = instruction.destSecurityCode;
                fundTransferInstruction.destSecurityName = instruction.destSecurityName;
                fundTransferInstruction.destCombiId = instruction.destCombiId;
                fundTransferInstruction.destCombiName = instruction.destCombiName;
                fundTransferInstruction.bulkType = instruction.bulkType;
                this.createInstruction(fundTransferInstruction, stockInfo);
                return { instruction: fundTransferInstruction, stockInfo: stockInfo };
            }
        } else if (insttype === '9') {
            // 获取证券信息
            let res: any = await this.getUnderNetStockList({
                paging: {
                    currentPage: 1,
                    pageSize: 10000,
                },
                stockNameOrCode: String(instruction.stockCode),
            });
            let stockInfo = res.list[0];
            if (!stockInfo) {
                return '错误的证券代码';
            } else {
                stockInfo.stockNameSt = stockInfo.stockName;
            }
            // if (moment(stockInfo.payLimitDate.toString()).isBefore(moment().format('YYYYMMDD'))) {
            //     return '输入证券已经申购截止，不允许再做网下申购！';
            // }

            if (
                (instruction.orderPrice && Number(instruction.orderPrice) < Number(stockInfo.lowerPrice)) ||
                Number(instruction.orderPrice) > Number(stockInfo.upperPrice)
            ) {
                return '申购价格须在价格区间[' + stockInfo.lowerPrice + '，' + stockInfo.upperPrice + ']内！';
            }
            // 组装指令
            let offlineSubscribeForm: any = new OfflineSubscribeForm();
            let offlineSubscribeInstruction = JSON.parse(JSON.stringify(offlineSubscribeForm.instruction));
            offlineSubscribeInstruction.correspondingIndex = this.correspondingIndex++;
            // futuresInstruction.reportCode = instruction.reportCode;
            offlineSubscribeInstruction.reportCode = stockInfo.reportCode;
            offlineSubscribeInstruction.stockCode = instruction.stockCode;
            offlineSubscribeInstruction.fundCode = fund.fundCode;
            offlineSubscribeInstruction.fundNameSt = String(fund.fundNameSt);
            offlineSubscribeInstruction.fundAccountCode = String(instruction.fundAccountCode);
            offlineSubscribeInstruction.fundAccountName = fundAccount.fundAccountName;
            offlineSubscribeInstruction.assetCode = fundAccount.assetCode;
            offlineSubscribeInstruction.assetName = fundAccount.assetName;
            offlineSubscribeInstruction.orderDirection = String(instruction.orderDirection);
            offlineSubscribeInstruction.instType = insttype;
            offlineSubscribeInstruction.investType = instruction.investType;
            offlineSubscribeInstruction.orderAmount = instruction.orderAmount;
            offlineSubscribeInstruction.orderPrice = instruction.orderPrice;
            // offlineSubscribeInstruction.orderBalance = instruction.orderBalance;
            offlineSubscribeInstruction.orderBalance = Number(instruction.orderPrice || 0) * Number(instruction.orderAmount || 0);
            offlineSubscribeInstruction.earnestBalance = instruction.earnestBalance;
            offlineSubscribeInstruction.instructionTypeName = instruction.instructionTypeName;
            offlineSubscribeInstruction.businClass = instruction.instructionTypeName;
            offlineSubscribeInstruction.businessType = offlineSubscribeInstruction.instructionTypeName;
            offlineSubscribeInstruction.opponentCode = instruction.opponentCode;

            this.createInstruction(offlineSubscribeInstruction, stockInfo);
            return { instruction: offlineSubscribeInstruction, stockInfo: stockInfo };
        } else if (insttype === '10') {
            // 获取证券信息
            let res = await this.getPrimaryBondInfo({
                bondInfo: {
                    bidTag: 1,
                },
                dictKey: String(instruction.stockCode),
                dictKeyName: '',
            });
            let stockInfo = res[0].bondInfo;
            stockInfo.stockNameSt = res[0].dictKeyName;
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let primaryBondOrder: any = new PrimaryBondOrder();
            let primaryBondInstruction = JSON.parse(JSON.stringify(primaryBondOrder.instruction));
            primaryBondInstruction.correspondingIndex = this.correspondingIndex++;
            primaryBondInstruction.fundCode = fund.fundCode;
            primaryBondInstruction.fundNameSt = String(fund.fundNameSt);
            primaryBondInstruction.fundAccountCode = String(instruction.fundAccountCode);
            primaryBondInstruction.fundAccountName = fundAccount.fundAccountName;
            primaryBondInstruction.assetCode = fundAccount.assetCode;
            primaryBondInstruction.assetName = fundAccount.assetName;
            primaryBondInstruction.orderDirection = String(instruction.orderDirection);
            primaryBondInstruction.orderPrice = instruction.orderPrice;
            primaryBondInstruction.orderAmount = instruction.orderAmount;
            primaryBondInstruction.orderBalance = instruction.orderBalance;
            primaryBondInstruction.instType = insttype;
            primaryBondInstruction.investType = instruction.investType;
            primaryBondInstruction.reportCode = stockInfo.reportCode;
            primaryBondInstruction.stockCode = instruction.stockCode;
            primaryBondInstruction.businessType = instruction.instructionTypeName;
            primaryBondInstruction.subject = instruction.subject;
            primaryBondInstruction.tenderWay = instruction.tenderWay;
            primaryBondInstruction.listDate = instruction.listDate;
            primaryBondInstruction.payDate = instruction.payDate;

            this.createInstruction(primaryBondInstruction, stockInfo);
            return { instruction: primaryBondInstruction, stockInfo: stockInfo };
        } else if (insttype == '14') {
            // 获取证券信息
            let res = await this.getStockReportSelectAsync(1, {
                dictKey: String(instruction.stockCode),
                dictKeyName: '',
            });
            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let refinancingOrder: any = new RefinancingRiskOrder();
            // eslint-disable-next-line camelcase
            let refinancingOrder_ins = JSON.parse(JSON.stringify(refinancingOrder.instruction));
            refinancingOrder_ins.correspondingIndex = this.correspondingIndex++;
            refinancingOrder_ins.instType = insttype;
            refinancingOrder_ins.fundCode = fund.fundCode;
            refinancingOrder_ins.reportCode = stockInfo.reportCode;
            refinancingOrder_ins.stockCode = String(instruction.stockCode);
            refinancingOrder_ins.fundNameSt = String(fund.fundNameSt);
            refinancingOrder_ins.fundAccountCode = String(instruction.fundAccountCode);
            refinancingOrder_ins.fundAccountName = fundAccount.fundAccountName;
            refinancingOrder_ins.assetCode = fundAccount.assetCode;
            refinancingOrder_ins.assetName = fundAccount.assetName;
            refinancingOrder_ins.investType = instruction.investType;

            refinancingOrder_ins.orderDirection = String(instruction.orderDirection);
            refinancingOrder_ins.orderAmount = instruction.orderAmount;
            refinancingOrder_ins.instructionTypeName = instruction.instructionTypeName;
            refinancingOrder_ins.businessType = instruction.instructionTypeName;
            refinancingOrder_ins.deadline = instruction.deadline;
            refinancingOrder_ins.rate = instruction.rate;
            this.createInstruction(refinancingOrder_ins, stockInfo);
            let item = { instruction: refinancingOrder_ins, stockInfo: stockInfo };
            return item;
        } else if (insttype == '15') {
            // let etfOrder: any = new ETFForm();

            // 获取证券信息
            let res = await getETFBasicInfo(instruction.stockCode);
            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let ETFFormObj: any = new ETFForm();
            let etfOrder = JSON.parse(JSON.stringify(ETFFormObj.orderForm));

            etfOrder.correspondingIndex = this.correspondingIndex++;
            etfOrder.instType = insttype;
            etfOrder.fundCode = fund.fundCode;
            etfOrder.reportCode = instruction.stockCode.split(' ')[0];
            etfOrder.stockCode = String(instruction.stockCode);
            etfOrder.stockName = stockInfo.stockName;
            etfOrder.fundNameSt = String(fund.fundNameSt);
            etfOrder.fundAccountCode = String(instruction.fundAccountCode);
            etfOrder.fundAccountName = fundAccount.fundAccountName;
            etfOrder.assetCode = fundAccount.assetCode;
            etfOrder.assetName = fundAccount.assetName;
            etfOrder.investType = instruction.investType;
            etfOrder.orderDirection = String(instruction.orderDirection);
            etfOrder.orderAmount = instruction.orderAmount;
            etfOrder.businessType = instruction.instructionTypeName;
            this.createInstruction(etfOrder, stockInfo);
            etfOrder.orderBalance = instruction.orderBalance;
            let item = { instruction: etfOrder, stockInfo: stockInfo };
            return item;
        } else if (insttype == '20') {
            //  非标
            // 获取证券信息
            let res = await this.getStockReportSelectAsync(20, {
                dictKey: String(instruction.stockCode),
                dictKeyName: '',
            });
            let stockInfo = res[0];
            if (!stockInfo) {
                return '错误的证券代码';
            }
            // 组装指令
            let refinancingOrder: any = new OffstandardForm();
            // eslint-disable-next-line camelcase
            let refinancingOrder_ins = JSON.parse(JSON.stringify(refinancingOrder.orderForm));
            refinancingOrder_ins.fundCode = fund.fundCode;
            refinancingOrder_ins.fundNameSt = String(fund.fundNameSt);
            refinancingOrder_ins.stockCode = String(instruction.stockCode);
            refinancingOrder_ins.stockNameSt = String(instruction.stockNameSt);
            refinancingOrder_ins.orderBalance = instruction.orderBalance / 10000;
            refinancingOrder_ins.instType = insttype;

            // refinancingOrder_ins.orderDirection = '1';
            // refinancingOrder_ins.instructionType = '20';
            // refinancingOrder_ins.businessType = 'FB';
            // refinancingOrder_ins.businClass = 'FB';
            // refinancingOrder_ins.stockType = 'U';
            // refinancingOrder_ins.marketCode = '6';
            this.createInstruction(refinancingOrder_ins, stockInfo);
            let item = { instruction: refinancingOrder_ins, stockInfo: stockInfo };
            return item;
        }
        return '错误的指令类型';
    }

    // 按钮事件 点击确认导入excel数据
    async settingImportValue(data: any) {
        this.importButtonDisabled = true;
        let instData = data[0];
        let importPledgeList = data[1];
        let importRowkeys = [];
        let importShowList = [];
        let importEngineList = [];

        for (let i = 0; i < instData.length; i++) {
            let instruction = instData[i];
            this.preHandleImportInstruction(instruction);

            let verify = this.verifyImportInfo(instruction);
            if (verify !== true) {
                this.yh_message_warn('第' + (i + 1) + '行:  ' + verify);
                return;
            }
            let item: any = await this.transformImport(instruction);
            if (!item.instruction) {
                this.yh_message_warn('第' + (i + 1) + '行:  ' + item);
                return;
            }
            let requestId = UUID() + '-' + moment();
            item.instruction.requestId = requestId;
            if (item.instruction.instructionType === '2') {
                let list: any = [];
                importPledgeList.forEach(ele => {
                    if (ele['instNo'] == item.instruction['instNo']) {
                        list.push(ele);
                    }
                });
                item.instruction.selectedPledgePOList = list;
            }
            await this.getOpponentCode(item.instruction.opponentCode);
            let opponentName = '';
            this.opponentCodeSelectData.forEach(ele => {
                if (ele.dictKey === item.instruction.opponentCode) {
                    opponentName = ele.dictKeyName;
                }
            });
            item.instruction.opponentName = opponentName;
            importRowkeys.push(requestId);
            importShowList.push(this.showInstructionForList(item));
            importEngineList.push(item);
        }

        // 全部成功
        let instDataSource = this.instDataSource;
        importShowList.filter(item => instDataSource.push(item));
        importEngineList.filter(item => this.orginalData.push(item));

        this.importDialog = false;
        console.log(instDataSource, 'instDataSource');
        debugger;

        this.instDataSource = JSON.parse(JSON.stringify(instDataSource));
        this.instTableMsg.returnData.data = JSON.parse(JSON.stringify(this.instDataSource));
        this.importButtonDisabled = false;
    }

    // 导入后 向列表渲染数据 仅用于展示
    showInstructionForList(item) {
        let instruction = item.instruction;
        let stockInfo = item.stockInfo;

        let showdata = {
            key: instruction.requestId,
            requestId: instruction.requestId,
            correspondingIndex: instruction.correspondingIndex,
            instType: instruction.instType,
            fundCode: instruction.fundCode,
            fundNameSt: instruction.fundNameSt,
            fundAccountCode: instruction.fundAccountCode,
            fundAccountName: instruction.fundAccountName,
            assetCode: instruction.assetCode,
            assetName: instruction.assetName,
            stockCode: stockInfo.stockCode,
            stockNameSt: stockInfo.stockNameSt || stockInfo.stockName,
            marketCode: instruction.marketCode,
            orderDirection: instruction.orderDirection,
            orderPriceType: instruction.orderPriceType,
            curName: stockInfo.curName,
            orderPrice: instruction.orderPrice,
            orderAmount: instruction.orderAmount,
            orderBalance: instruction.orderBalance,
            orderBalances: instruction.orderBalances, // 合约价值
            earnestBalance: instruction.earnestBalance,
            depositRate: instruction.depositRate,
            mutureDate: instruction.mutureDate,
            depositType: instruction.depositType,
            noticeDays: instruction.noticeDays,
            instructionType: instruction.instructionType,
            instructionTypeName: instruction.instructionTypeName,
            opponentCode: instruction.opponentCode,
            opponentName: instruction.opponentName,
            exchangeType: instruction.exchangeType,
            winningRate: instruction.winningRate,
            investType: instruction.investType,
            deadline: instruction.deadline,
            rate: instruction.rate,
            clearSpeed: instruction.clearSpeed,
            fullPrice: instruction.fullPrice,
            stockFaceBalance: instruction.stockFaceBalance,
            orderRate: instruction.orderRate,
            firstSettleDate: instruction.firstSettleDate, // 结算日期
            endSettleDate: instruction.endSettleDate,
            startDate: instruction.startDate,
            advanceLimitFlag: instruction.advanceLimitFlag,

            // 基金转换相关字段
            destSecurityCode: instruction.destSecurityCode,
            destSecurityName: instruction.destSecurityName,
            destCombiId: instruction.destCombiId,
            destCombiName: instruction.destCombiName,
            bulkType: instruction.bulkType,
            showType: instruction.showType,
            // 一级债相关字段
            subject: instruction.subject,
            listDate: instruction.listDate,
            payDate: instruction.payDate,
            tenderWay: instruction.tenderWay,

            // 上交所固收
            yield: instruction.yield, // 到期收益率
            fullBalance: instruction.fullBalance,
            totalInterest: instruction.totalInterest, // 总应计利息
            targetType: instruction.targetType, // 目标类型
            // ETF
            directMode: instruction.directMode,
            etfStockListInfoDTOList: this.stockTableData,
            execType: stockInfo.execType,
        };
        return showdata;
    }

    /**
     * 预处理指令
     */
    preHandleImportInstruction(instruction) {
        debugger;
        if (instruction.instType) {
            let instTypeMapping = DictionConstUtil.ReversePojo(this.instTypeMap);
            if (!instTypeMapping[instruction.instType]) {
                return '指令类型错误';
            }
            instruction.instType = instTypeMapping[instruction.instType];
        }
        if (instruction.orderDirection) {
            let orderDirectionMapping = DictionConstUtil.ReversePojo(this.OrderDirection);
            if (instruction.orderDirection === '申购') {
                instruction.orderDirection = 'C';
            } else if (orderDirectionMapping[instruction.orderDirection]) {
                instruction.orderDirection = orderDirectionMapping[instruction.orderDirection];
            }
        }
        if (instruction.instructionTypeName) {
            let allBusinessTypeMapping = DictionConstUtil.ReversePojo(this.AllBusinessTypeMap);
            if (allBusinessTypeMapping[instruction.instructionTypeName]) {
                instruction.instructionTypeName = allBusinessTypeMapping[instruction.instructionTypeName];
            }
        }
        if (instruction.clearSpeed) {
            let clearSpeedTypeMapping = DictionConstUtil.ReversePojo(this.clearSpeedType);
            if (clearSpeedTypeMapping[instruction.clearSpeed]) {
                instruction.clearSpeed = clearSpeedTypeMapping[instruction.clearSpeed];
            }
        }
        if (instruction.depositType) {
            let depositTypeMapping = DictionConstUtil.ReversePojo(this.DepositType);
            if (depositTypeMapping[instruction.depositType]) {
                instruction.depositType = depositTypeMapping[instruction.depositType];
            }
        }
        if (instruction.advanceLimitFlag) {
            let advanceLimitFlagTypeMapping = DictionConstUtil.ReversePojo(this.Invest.advanceLimitFlagType);
            if (advanceLimitFlagTypeMapping[instruction.advanceLimitFlag]) {
                instruction.advanceLimitFlag = advanceLimitFlagTypeMapping[instruction.advanceLimitFlag];
            }
        }
        if (instruction.bulkType) {
            let bulkTypeMapping = DictionConstUtil.ReversePojo(this.Invest.bulkType);
            if (bulkTypeMapping[instruction.bulkType]) {
                instruction.bulkType = bulkTypeMapping[instruction.bulkType];
            }
        }
        if (instruction.tenderWay) {
            let tenderWayMapping = DictionConstUtil.ReversePojo(this.Invest.tenderWayType);
            if (tenderWayMapping[instruction.tenderWay]) {
                instruction.tenderWay = tenderWayMapping[instruction.tenderWay];
            }
        }
        if (instruction.subject) {
            let subjectMapping = DictionConstUtil.ReversePojo(this.Invest.bidSubjectType);
            if (subjectMapping[instruction.subject]) {
                instruction.subject = subjectMapping[instruction.subject];
            }
        }

        // 投资类型
        if (instruction.investType) {
            let investTypeMapping = DictionConstUtil.ReversePojo(this.Invest.investType);
            if (investTypeMapping[instruction.investType]) {
                instruction.investType = investTypeMapping[instruction.investType];
            }
        }
    }

    /* ************************** 导入end ************************* */

    /**
     * 获取交易所指令的表单验证参数
     */
    getExChangeOrderVerify(instruction, stockInfo) {
        let verify = {
            fundCode: '产品代码',
            fundAccountCode: '组合编码',
            reportCode: '证券代码',
            orderDirection: '委托方向',
            //
            businessType: '业务类型',
        };
        let extraField: any = {};
        if (instruction.showType === 1) {
            extraField = {
                // orderPrice: '指令价格',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
            if (stockInfo.stockType === 'a') {
                // 股票申购
                extraField.winningRate = '预估中签率';
            }
        } else if (instruction.showType === 2) {
            extraField = {
                deadline: '期限',
                rate: '费率',
                // counterparty:'交易对手',
                businessType: '业务类型',
                orderAmount: '融出数量',
            };
        } else if (instruction.showType === 3) {
            extraField = {};
            if (stockInfo.stockType === 'k') {
                // 债券申购
                extraField.winningRate = '预估中签率';
            }
            if (stockInfo.quoteType === '1') {
                // 是否净价
                // extraField.netPrice = '净价'
                extraField.orderAmount = '指令数量';
                extraField.netMoney = '净价金额';
            } else {
                // extraField.allPrice='全价价格'
                extraField.orderAmount = '指令数量';
                extraField.allMoney = '全价金额';
            }
        } else if (instruction.showType === 4 || instruction.showType === 5) {
            extraField = {
                // orderPrice: '指令价格',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
        } else if (instruction.showType === 6) {
            extraField = {
                orderRate: '回购利率',
                orderBalance: '指令金额',
            };
        } else if (instruction.showType == 8) {
            extraField = {
                orderPrice: '净价价格',
                orderAmount: '指令数量',
                orderBalance: '净价金额',
            };
        }
        return { ...verify, ...extraField };
    }

    // 组装指令信息
    createInstruction(instruction, stockInfo) {
        console.log(instruction, 'createInstruction');

        instruction.outerOrderCode = instruction.requestId;
        instruction.orderUser = getUser().userCode;
        instruction.orderPurpose = '15';
        if (instruction.instType !== '7') {
            instruction.investType = '1';
        }
        instruction.orderLevel = '0';
        instruction.remark = ' ';
        instruction.instructionType = this.InstTypePojo[instruction.instType];
        if (instruction.showType && instruction.showType === 8) {
            instruction.instructionType = '13';
        }
        instruction.orderType = '1';
        if (instruction.instType === '1') {
            // 交易所债券
            if (stockInfo.stockType === '5') {
                instruction.orderBalance = instruction.fullBalance;
                instruction.orderPrice = instruction.fullPrice;
            } else {
                instruction.orderBalance = instruction.netBalance;
                instruction.orderPrice = instruction.netPrice;
            }
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = '1';
            instruction.instructionType = '1';
            instruction.instructionTypeName = '交易所网上';
        } else if (instruction.instType === '2') {
            // 银行间债券
            instruction.orderPriceType = '1';
            let amount = Number(instruction.stockFaceBalance) / Number(stockInfo.facePrice);
            instruction.orderAmount = amount === Infinity ? 0 : amount;
            instruction.marketCode = stockInfo.marketCode;
            instruction.instructionType = '1';
            instruction.businClass = instruction.businessType;
            instruction.instructionTypeName = instruction.businessType;
            instruction.interest = instruction.totalInterest;
            instruction.mutureDate = instruction.firstSettleDate;
        } else if (instruction.instType === '3') {
            // 交易所回购
            instruction.orderPrice = instruction.orderRate;
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = '1';
            instruction.instructionType = '2';
            instruction.instructionTypeName = '交易所网上';
            instruction.interest = instruction.estimateInterest;
        } else if (instruction.instType === '4') {
            // 银行间回购
            instruction.marketCode = '5';
            instruction.orderPriceType = '1';
            instruction.orderAmount = Number(instruction.orderBalance) / 100;
            instruction.orderPrice = instruction.orderRate;
            instruction.reportCode = stockInfo.reportCode;
            instruction.businClass = instruction.businessType;
            instruction.instructionType = '2';
            instruction.instructionTypeName = instruction.businessType;
            instruction.interest = instruction.shouldInterest;
            instruction.pledgePOList = this.handleSelectdPledgeList(instruction.selectedPledgePOList);
        } else if (instruction.instType === '5') {
            if (instruction.orderDirection == 'F') {
                // 存款
                instruction.orderDirection = 'F';
                // instruction.advanceType = ' ';
            } else if (instruction.orderDirection == 'i') {
                // 存款指令
                instruction.outerOrderCode = instruction.requestId;
                instruction.orderUser = getUser().userCode;
                instruction.orderPurpose = '15';
                instruction.investType = '1';

                instruction.orderLevel = '0';
                instruction.remark = ' ';
                instruction.orderDirection = 'i';
            }
            instruction.orderPrice = '1';
            instruction.orderPriceType = '1';
            instruction.instructionType = '3';
            instruction.orderAmount = instruction.orderBalance;
            instruction.bankBranchCode = ' ';
            instruction.reportCode = stockInfo.reportCode;
            instruction.stockCode = stockInfo.stockCode;
            instruction.businClass = instruction.businessType;
            instruction.endSettleDate = instruction.mutureDate;
            instruction.startDate = instruction.depositStartDate;
            instruction.marketCode = '6';
            instruction.instructionTypeName = instruction.businessType;
        } else if (instruction.instType === '6' || instruction.instType === '11') {
            // 交易所指令
            if (!instruction.exchangeType && instruction.instType === '6') {
                instruction.exchangeType = instruction.showType;
            }
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = instruction.businessType;
            instruction.instructionType = '4';
            instruction.instructionTypeName = instruction.businessType;
            if (instruction.showType == 2) {
                // instruction.instructionType = '14';
                instruction.instructionType = '4';
            } else if (instruction.showType == 3) {
                if (stockInfo.quoteType === '1') {
                    instruction.orderPrice = instruction.netPrice;
                    instruction.orderBalance = instruction.netMoney;
                } else {
                    instruction.orderPrice = instruction.allPrice;
                    instruction.orderBalance = instruction.allMoney;
                }
            } else if (instruction.showType == 6) {
                instruction.orderAmount = 0;
                instruction.orderPrice = 0;
                // instruction.instructionType = '2'
                instruction.instructionType = '4';
            } else if (instruction.showType == 8) {
                instruction.instructionType = '13';
                instruction.outerOrderCode = 'rsfi' + UUID() + '-' + new Date().getTime();
                instruction.requestId = 'sfi' + UUID() + '-' + new Date().getTime();
                instruction.orderPriceType = '1';
                instruction.orderLevel = '1';
                instruction.orderPurpose = '1';
                instruction.clearSpeed = '1';
                instruction.investType = '1';
                instruction.operatorName = getUser().userName;
                instruction.orderUser = getUser().userCode;
                // instruction.fullPrice = Number(instruction.orderPrice) + Number(stockInfo?.tDayInterest);
                // instruction.totalInterest = Number(instruction.orderAmount) * Number(stockInfo?.tDayInterest || 0);
                // instruction.fullBalance = Number(instruction.orderBalance || 0) + Number(instruction.totalInterest || 0);
            }
        } else if (instruction.instType === '7') {
            // 期货指令
            instruction.cancelType = '3';
            instruction.clearSpeed = '';
            instruction.marketCode = stockInfo.marketCode;
            instruction.operatorName = instruction.orderUser;
            instruction.orderLevel = '1';
            instruction.orderPriceType = '1';
            instruction.orderPurpose = '1';
            instruction.outerOrderCode = 'fg' + UUID() + '-' + new Date().getTime();
            instruction.requestId = 'rfg' + UUID() + '-' + new Date().getTime();
            instruction.businClass = instruction.businessType;
            instruction.stockType = stockInfo.stockType;
            instruction.instructionTypeName = instruction.businessType;
        } else if (instruction.instType === '8') {
            // 场外开基指令
            instruction.bulkType = instruction.bulkType || '2';
            instruction.cancelType = '3';
            instruction.investType = '1';
            instruction.marketCode = stockInfo.marketCode;
            instruction.operatorName = instruction.orderUser;
            instruction.orderLevel = '1';
            instruction.orderPriceType = '1';
            instruction.orderPurpose = '1';
            instruction.outerOrderCode = 'cof' + UUID() + '-' + new Date().getTime();
            instruction.requestId = 'rcof' + UUID() + '-' + new Date().getTime();
            instruction.businClass = instruction.businessType;
            instruction.stockType = stockInfo.stockType;
            instruction.instructionTypeName = instruction.businessType;
        } else if (instruction.instType === '9') {
            // 网下申购指令
            instruction.cancelType = '3';
            instruction.investType = '1';
            instruction.marketCode = stockInfo.marketNo;
            instruction.stockNameSt = stockInfo.stockName;
            instruction.operatorName = instruction.orderUser;
            instruction.orderLevel = '1';
            instruction.orderPriceType = '1';
            instruction.orderPurpose = '1';
            instruction.outerOrderCode = 'unp' + UUID() + '-' + new Date().getTime();
            instruction.requestId = 'runp' + UUID() + '-' + new Date().getTime();
            instruction.businClass = instruction.businessType;
            instruction.instructionTypeName = instruction.businessType;
        } else if (instruction.instType === '10') {
            instruction.orderLevel = '1';
            instruction.orderPurpose = '1';
            instruction.instructionType = '5';
            instruction.referencedYield = '0';

            instruction.marketCode = stockInfo.marketCode;
            instruction.outerOrderCode = 'tob' + UUID() + '-' + new Date().getTime();
            instruction.requestId = 'rtob' + UUID() + '-' + new Date().getTime();
            instruction.businClass = instruction.businessType;
            instruction.instructionTypeName = instruction.businessType;
        } else if (instruction.instType == '14') {
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = instruction.businessType;
            instruction.instructionType = '14'; //
            instruction.instructionTypeName = instruction.businessType;
            // instruction.orderPrice = instruction.orderPrice ? instruction.orderPrice : instruction.lastPriceOrorderPrice;
            instruction.orderPrice = instruction.lastPriceOrorderPrice;
            instruction.orderBalance = accMul(instruction.orderPrice, instruction.orderAmount);
        } else if (instruction.instType == '15') {
            instruction.directMode = '8'; // 计算模式为 无序非从严合并计算
            instruction.calculateEntryGroup = this.selectEntryGroupCode.calculateEntryGroup; // 计算条目组
            instruction.excludeEntryGroup = this.selectEntryGroupCode.excludeEntryGroup; // 排除条目组
            instruction.marketCode = stockInfo.marketCode;
            instruction.execType = stockInfo.execType;
            instruction.reportCode = instruction.stockCode.split(' ')[0] || '';
            instruction.etfStockListInfoDTOList = this.stockTableData;
            instruction.orderBalance = instruction.orderBalance * 10000; // 按最小单位元传给后端
        } else if (instruction.instType == '20') {
            console.log(stockInfo, 'stockInfo');

            // 发起试算 组装非标数据
            // let newInstruction = {
            //     fundCode: instruction.fundCode,
            //     stockCode: instruction.stockCode,
            //     orderBalance: instruction.orderBalance * 10000,
            //     instType: '20'
            // };
            instruction.orderDirection = '1';
            instruction.businessType = 'FB';
            instruction.businClass = 'FB';
            instruction.stockType = stockInfo.stockType;
            instruction.marketCode = stockInfo.marketCode;
            instruction.reportCode = stockInfo.reportCode;
            instruction.orderBalance = instruction.orderBalance * 10000;
        }
        return instruction;
    }

    // 校验指令信息
    async verifyInstructionParam(instruction, stockInfo) {
        console.log('verifyP:', instruction);

        let verify: any = {};
        if (!instruction || !instruction.fundCode) {
            this.yh_message_warn(' 请完善指令信息!');
            return false;
        }
        if (instruction.instType === '1') {
            verify = {
                fundCode: '产品代码',
                orderPriceType: '价格模式',
                fundAccountCode: '组合编码',
                targetType: '目标类型',
                reportCode: '证券代码',
                orderAmount: '指令数量',
                orderDirection: '委托方向',
                netBalance: '净价金额',
                netPrice: '净价价格',
                fullPrice: '全价价格',
            };
        } else if (instruction.instType === '2') {
            verify = {
                fundCode: '产品代码',
                fullPrice: '全价价格',
                fundAccountCode: '组合编码',
                stockFaceBalance: '券面总额',
                reportCode: '证券代码',
                firstSettleDate: '结算日期',
                orderDirection: '订单方向',
                orderBalance: '净价金额',
                clearSpeed: '清算速度',
                totalInterest: '总应计利息',
                orderPrice: '净价价格',
                settlementBalance: '结算金额',
                //
                businessType: '业务类型',
            };
        } else if (instruction.instType === '3') {
            verify = {
                fundCode: '产品代码',
                orderPriceType: '价格模式',
                fundAccountCode: '组合编码',
                orderAmount: '回购数量',
                reportCode: '证券代码',
                orderBalance: '回购金额',
                orderDirection: '委托方向',
                estimateInterest: '预计应计利息',
                orderRate: '回购利率',
                estimateRepurchaseBalance: '预计到期购回金额',
            };
        } else if (instruction.instType === '4') {
            verify = {
                fundCode: '产品代码',
                endSettleDate: '到期日期',
                fundAccountCode: '组合编码',
                orderRate: '回购利率',
                repoDay: '回购天数',
                orderBalance: '回购金额',
                orderDirection: '委托方向',
                factUseMoney: '实际占款天数',
                clearSpeed: '清算速度',
                shouldInterest: '应计利息',
                firstSettleDate: '结算日期',
                expirePayBalance: '到期购回金额',
                // opponentCode: '交易对手',
                businessType: '业务类型',
            };
            if (instruction.orderRate == 0.0) {
                this.yh_message_warn('请输入正确的回购利率');
                return false;
            }
            if (instruction.orderRate > 100) {
                this.yh_message_warn('回购利率在0-100(包含)之间');
                return false;
            }
            if (stockInfo.stockCode) {
                let res = await foundStockExistAsync({ dictKey: stockInfo.stockCode });
                if (!instruction.repoDay && instruction.repoDay !== '') {
                    if (Number(res) === 0) {
                        this.yh_message_warn('回购天数不合理，请重新输入');
                        return;
                    }
                }
            }

            if (instruction.firstSettleDate && instruction.endSettleDate) {
                let beginDate = new Date(instruction.firstSettleDate.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3'));
                let endDate = new Date(instruction.endSettleDate.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3'));
                if (beginDate > endDate) {
                    this.yh_message_warn('到期日期必须大于等于结算日期');
                    return false;
                }
            }
            // if (!this.selectedList.length) {
            //     this.yh_message_warn('委托方向为"融资回购"，必须输入质押券！');
            //     // return false;
            // }

            for (let index = 0; index < this.selectedList.length; index++) {
                if (this.selectedList[index]['totalFacePrice'] <= 0) {
                    this.yh_message_warn('"券面总额"须大于0！');
                    return false;
                }
                if (this.selectedList[index]['pledgedQty'] > this.selectedList[index]['currentAmount']) {
                    this.yh_message_warn('"质押数量"须小于等于"实时持仓数量"！');
                    return false;
                }
                if (moment(this.selectedList[index]['endDate']).isBefore(moment(instruction.endSettleDate).format('YYYYMMDD'))) {
                    this.yh_message_warn('质押券的"债券到期日"不能早于"到期结算日期"！');
                    return false;
                }
            }
        } else if (instruction.instType === '5') {
            if (instruction.orderDirection == 'F') {
                // 存款
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    depositType: '存款类型',
                    bankCode: '银行总行',
                    advanceLimitFlag: '提前支取限制',
                    depositRate: '存款利率',
                    orderBalance: '存款金额',
                    depositStartDate: '起息日',
                    depositLimitTime: '存款期限',
                    mutureDate: '到期日期', //
                    drawDate: '支取日期',

                    depositInterest: '存款利息', //
                    expireBalance: '到期金额',

                    // businessType: '业务类型',
                };
                if (instruction.depositType == '2') {
                    delete verify.mutureDate;
                    delete verify.depositLimitTime;
                    if (instruction.advanceType == '1') {
                        delete verify.depositInterest;
                        delete verify.drawDate;
                    }
                } else {
                    // 1和3
                    delete verify.drawDate;
                    if (instruction.mutureType == '1') {
                        delete verify.mutureDate;
                    } else {
                        delete verify.depositLimitTime;
                    }
                }
            } else if (instruction.orderDirection == 'i') {
                verify = {
                    fundCode: '产品代码',
                    receiptNo: '存单号',
                    fundAccountCode: '组合编码',
                    drawInterest: '利息金额',
                    balance: '兑付金额',
                    drawDate: '支取日期',
                };
            }
        } else if (instruction.instType === '6' || instruction.instType === '11') {
            verify = this.getExChangeOrderVerify(instruction, stockInfo);
            if (instruction.businessType === 'I') {
                verify.yield = '到期收益率';
                verify.opponentCode = '交易对手';
            }
        } else if (instruction.instType === '7') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                reportCode: '合约代码',
                orderDirection: '委托方向',
                orderPrice: '指令价格',
                orderAmount: '指令数量',
                // orderBalance: '合约价值',
                investType: '投资类型',
                businessType: '业务类型',
            };
        } else if (instruction.instType === '8') {
            if (instruction.orderDirection !== 'E') {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '组合编码',
                    reportCode: '证券代码',
                    orderDirection: '委托方向',
                    //
                    businessType: '业务类型',
                    orderAmount: '指令数量',
                    orderBalance: '指令金额',
                };
                if (instruction.orderDirection === 'D' || instruction.orderDirection === 'p') {
                    delete verify.orderAmount;
                } else if (instruction.orderDirection === 'q') {
                    delete verify.orderBalance;
                }
            } else {
                verify = {
                    fundCode: '产品代码',
                    fundAccountCode: '转出组合编号',
                    destCombiId: '转入组合编号',
                    reportCode: '转出证券代码',
                    destSecurityCode: '转入证券代码',
                    orderAmount: '转换份额',
                };
                if (instruction.reportCode && instruction.destSecurityCode) {
                    if (instruction.reportCode === instruction.destSecurityCode.split(' ')[0]) {
                        this.yh_message_warn('转入证券与转出证券不能相同！');
                        return false;
                    }
                    if (this.intoStockInfo.stockType !== this.stockInfo.stockType) {
                        this.yh_message_warn('进行转换的两个证券的类别必须相同！');
                        return false;
                    }
                }
                if (instruction.orderAmount === '0.00') {
                    this.yh_message_warn('转换份额不能为0！');
                    return false;
                } else if (Number(instruction.orderAmount) > 999999999999.99) {
                    this.yh_message_warn('转换份额不能超过999999999999.99！');
                    return false;
                }
            }
        } else if (instruction.instType === '9') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                reportCode: '证券代码',
                orderDirection: '委托方向',
                orderPrice: '申购价格',
                orderAmount: '申购数量',
                orderBalance: '申购金额',
                opponentCode: '交易对手',
                earnestBalance: '申购定金',
            };
            // if (moment(this.stockInfo.payLimitDate.toString()).isBefore(moment().format('YYYYMMDD'))) {
            //     this.yh_message_warn('输入证券已经申购截止，不允许再做网下申购！');
            //     return false;
            // }

            if (
                (instruction.orderPrice && Number(instruction.orderPrice) < Number(this.stockInfo.lowerPrice)) ||
                Number(instruction.orderPrice) > Number(this.stockInfo.upperPrice)
            ) {
                this.yh_message_warn('申购价格须在价格区间[' + this.stockInfo.lowerPrice + '，' + this.stockInfo.upperPrice + ']内！');
                return false;
            }
            if (instruction.orderAmount !== '' || instruction.orderAmount !== undefined) {
                if (instruction.orderAmount === '0.00') {
                    this.yh_message_warn('申购数量不能为0！');
                    return false;
                } else if (Number(instruction.orderAmount) > 999999999999.0) {
                    this.yh_message_warn('申购数量不能超过999999999999.00！');
                    return false;
                }
            }
        } else if (instruction.instType === '10') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                reportCode: '证券代码',
                orderDirection: '委托方向',
                // payDate: '缴款日期',
                listDate: '上市日期',
                orderPrice: '价格',
                orderBalance: '投标金额',
            };
        } else if (instruction.instType === '14') {
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                reportCode: '证券代码',
                orderDirection: '委托方向',
                //
                businessType: '业务类型',
                deadline: '期限',
                rate: '费率',
                // counterparty:'交易对手',
                orderAmount: '融出数量',
            };
        } else if (instruction.instType === '15') {
            // ETF指令
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
        } else if (instruction.instType === '20') {
            verify = {
                fundCode: '产品代码',
                stockCode: '证券代码',
                orderBalance: '指令金额',
            };
        }

        if (instruction.orderDirection == '98' && !instruction.advanceSettleDate) {
            this.yh_message_warn('提前了结日期不可为空');
            return false;
        } else if (instruction.orderDirection == 'M' && !instruction.originDealNo) {
            this.yh_message_warn('合约编号不可为空');
            return false;
        }

        for (let key in verify) {
            if (!instruction[key] && key !== 'orderPriceType') {
                this.yh_message_warn(verify[key] + ' 不可为空');
                return false;
            }
            if (['orderAmount', 'orderBalance', 'netMoney', 'allMoney'].includes(key)) {
                if (instruction[key] === '0.00') {
                    this.yh_message_warn(verify[key] + '必须大于0！');
                    return false;
                } else if (Number(instruction[key]) > 999999999999.99) {
                    this.yh_message_warn(verify[key] + '不能超过999999999999.99！');
                    return false;
                }
            }
        }

        // 期货指令校验所选产品和证券是否含有期货保证金比例参数
        if (instruction.instType === '7') {
            if (!this.hasFutureRatio) {
                this.yh_message_warn('所选产品和证券未查询到对应的期货保证金比例参数信息，请重新选择');
                return false;
            }
        }

        // ETF指令 基金赎回时校验数量
        if (instruction.instType == '15') {
            let flag = false;
            if (instruction.orderDirection == 'Q') {
                if (!this.stockTableData.length) {
                    this.yh_message_warn('所选基金没有对应成分股');
                    return false;
                }
                for (let index = 0; index < this.stockTableData.length; index++) {
                    const ele = this.stockTableData[index];
                    if (ele.actualRedeemAmount > ele.availableAmount) {
                        this.yh_message_warn(
                            '赎回数量' +
                                ele.actualRedeemAmount +
                                '（单位份额' +
                                ele.stockAmount +
                                '）大于可用数量' +
                                ele.availableAmount +
                                '，请重新输入！'
                        );
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                return false;
            }
        }

        return true;
    }

    /**
     * 实际占款天数计算公式   实际占款天数=到期日期-结算日期
     */
    calcFactUseMoney(instruction) {
        if (!instruction.endSettleDate || !instruction.firstSettleDate) {
            return '';
        }
        return moment(instruction.endSettleDate, 'YYYYMMDD').diff(moment(instruction.firstSettleDate, 'YYYYMMDD'), 'days').toString();
    }

    // 补零
    fillZero(n) {
        let result = n.toString().length === 1 ? '0' + n : n;
        return result;
    }

    // 时间戳转换 yyyy-MM-dd
    formatTime(t = new Date()) {
        let d = new Date(t);
        let year = d.getFullYear();
        let month = d.getMonth() + 1;
        let date = d.getDate();
        let hours = d.getHours();
        let minutes = d.getMinutes();
        let seconds = d.getSeconds();
        let result = `${year}-${this.fillZero(month)}-${this.fillZero(date)} ${this.fillZero(hours)}:${this.fillZero(minutes)}:${this.fillZero(
            seconds
        )}`;
        return result;
    }

    handleTest() {
        if (
            this.activeKey == '5' &&
            this.instructionCache[this.activeKey].orderDirection === 'i' &&
            this.instructionCache[this.activeKey].advanceLimitFlag == '1'
        ) {
            this.$confirm('该存单不可提前支取，确定要进行提前兑付吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.handlecCalculate();
                })
                .catch(() => {
                    this.yh_message_info('已取消');
                });
        } else {
            this.handlecCalculate();
        }
    }

    // 试算
    async handlecCalculate() {
        // 自动填上到期日期和实际占款天数
        if (this.activeKey === '4') {
            if (this.instructionCache[this.activeKey].repoDay && this.instructionCache[this.activeKey].repoDay > 366) {
                this.yh_message_warn('回购天数不能超过366天，请重新输入');
                return;
            }
            if (!this.instructionCache[this.activeKey].endSettleDate && this.instructionCache[this.activeKey].endSettleDate !== '') {
                this.instructionCache[this.activeKey].endSettleDate = this.calcEndSettleDate(this.instructionCache[this.activeKey]).toString();
                this.instructionCache[this.activeKey].factUseMoney = this.calcFactUseMoney(this.instructionCache[this.activeKey]);
            }
            if (
                this.instructionCache[this.activeKey].factUseMoney &&
                Number(this.instructionCache[this.activeKey].factUseMoney) < Number(this.instructionCache[this.activeKey].repoDay)
            ) {
                this.yh_message_warn('实际占款天数不能小于回购天数，请重新输入');
                return;
            }
        }

        if (this.activeKey == '15') {
            // ETF指令  需先点击计算才能试算
            if (!this.stockTableCalcState) {
                this.yh_message_warn('请先计算！');
                return;
            }
        }

        let instruction = JSON.parse(JSON.stringify(this.instructionCache[this.activeKey] || {}));
        let stockInfo = this.stockInfoCache[this.activeKey] || {};
        if (!instruction) {
            this.yh_message_warn('请填写相关信息');
            return;
        }

        instruction.requestId = UUID() + '-' + new Date().getTime();
        instruction.instType = this.activeKey;
        let verInt = await this.verifyInstructionParam(instruction, stockInfo);
        if (!verInt) {
            return;
        }
        instruction = this.createInstruction(instruction, stockInfo);

        this.calcLoading = true;
        instruction.orderPrice = instruction.orderPrice ? instruction.orderPrice : '0';
        let start = window.performance.now();
        let instructionType = '';
        if (instruction.showType == '6') {
            instructionType = '4';
            console.log('回购指令: showType === 6');
            instruction.orderPrice = instruction.orderRate;
        } else if (instruction.showType == '8') {
            instructionType = '13';
        } else {
            instructionType = this.InstTypePojo[instruction.instType];
        }

        // 获取当前提交时间 (试算/下单时间)
        this.calcTime = this.formatTime(new Date());
        let instList = [];
        instList.push(instruction);
        instList.map((item: any) => {
            if (item.instType == '5') {
                item.depositRate = accDiv(item.depositRate, 100);
            }
        });
        trialCalculate({
            orderType: '1',
            // directMode: '1',
            multiType: '2',
            requestId: instruction.requestId,
            instructionType: instructionType,
            // instructionType: instruction.showType == '6' ? '4' : this.InstTypePojo[instruction.instType],
            outOrderBatchCode: UUID() + new Date().getTime(),
            tradeUser: getUser().userCode,
            calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
            excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
            instList: instList,
            directMode: this.directMode,
        })
            .then((res: any) => {
                // 风控结果
                this.riskResult = res.thresholdType;
                let end = window.performance.now();
                // 计算耗时
                this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
                this.yh_message_success('提交试算信息成功');
                let stockInfo = JSON.parse(JSON.stringify(this.stockInfoCache[this.activeKey] || {}));
                this.stockInfoPojo = JSON.parse(JSON.stringify(stockInfo));
                let data = res.resultList || [];
                // 根据产品代码 匹配产品名称
                data.forEach(ele => {
                    ele.requestId = res.requestId;
                    if ((!ele.stockCode || ele.stockCode === ' ') && this.stockInfo) {
                        ele.stockCode = this.stockInfo.stockCode || ' ';
                    }
                    // 风险类型
                    ele.entryType2 = this.entryType[ele.entryType];
                    // 比较方向
                    // ele.compareType2 = this.compareDirection[ele.compareType];
                    for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                        const item = this.fundCodeSelectData[i];
                        if (ele.fundCode === item.fundCode) {
                            ele.fundNameSt = item.fundNameSt;
                        }
                    }
                    ele.stockNameSt = this.stockInfoPojo.stockNameSt || this.stockInfoPojo.stockName;
                });
                this.testTable = JSON.parse(JSON.stringify(data));
                this.riskResultSourceList = JSON.parse(JSON.stringify(this.testTable));
                this.handelThresholdTypeFilter();
                this.calcLoading = false;
            })
            .catch(() => {
                this.testTable = [];
                this.riskResultSourceList = JSON.parse(JSON.stringify(this.testTable));
                this.calcLoading = false;
                this.riskResult = '';
                this.calcTime = '';
                this.takeTime = '';
            });
    }

    // 风险试算
    handleRiskCalculate() {
        this.handleRefresh('2');
        setTimeout(() => {
            let selectedRowKeys = this.selectedRowKeys;
            let instructions = this.orginalData
                .map((item: any) => {
                    if (selectedRowKeys.includes(item.instruction['requestId'])) {
                        let instruction = item.instruction;
                        let stockInfo = item.stockInfo;

                        let requestId = UUID() + '-' + new Date().getTime();
                        // 原先instructionType的取值方法
                        // instruction.exchangeType == '6' ? '2':InstTypePojo[instruction.instType]
                        return {
                            correspondingIndex: instruction.correspondingIndex,
                            requestId: requestId,
                            fundCode: instruction.fundCode,
                            instructionType: instruction.instructionType,
                            orderPriceType: instruction.orderPriceType,
                            fundAccountCode: instruction.fundAccountCode,
                            targetType: instruction.targetType,
                            reportCode: instruction.reportCode,
                            orderAmount: instruction.orderAmount,
                            orderDirection: instruction.orderDirection,
                            netBalance: instruction.netBalance,
                            netPrice: instruction.netPrice,
                            fullBalance: instruction.fullBalance,
                            earnestBalance: instruction.earnestBalance,
                            fullPrice: instruction.fullPrice,
                            orderUser: getUser().userCode,
                            depositRate: instruction.depositRate,
                            depositStartDate: instruction.depositStartDate,
                            depositType: instruction.depositType,
                            mutureDate: instruction.mutureDate,
                            noticeDays: instruction.noticeDays,
                            depositInterest: instruction.depositInterest,
                            expireBalance: instruction.expireBalance,
                            bankCode: instruction.bankCode,
                            advanceType: instruction.advanceType,
                            bankBranchCode: instruction.bankBranchCode,
                            advanceLimitFlag: instruction.advanceLimitFlag,
                            orderType: instruction.orderType,
                            clearSpeed: instruction.clearSpeed,
                            firstSettleDate: instruction.firstSettleDate,
                            endSettleDate: instruction.endSettleDate,
                            repoDay: instruction.repoDay,
                            remark: instruction.remark,
                            opponentCode: instruction.opponentCode,
                            marketCode: stockInfo.marketCode || stockInfo.marketNo,
                            stockCode: stockInfo.stockCode,
                            stockNameSt: stockInfo.stockNameSt,
                            fundNameSt: instruction.fundNameSt,
                            fundAccountName: instruction.fundAccountName,
                            assetCode: instruction.assetCode,
                            assetName: instruction.assetName,
                            orderBalance: instruction.orderBalance,
                            orderPrice: instruction.orderPrice ? instruction.orderPrice : '0',
                            investType: instruction.investType,
                            orderLevel: instruction.orderLevel,
                            orderPurpose: instruction.orderPurpose,
                            outerOrderCode: requestId,
                            winningRate: instruction.winningRate,
                            businClass: instruction.businClass,
                            businessType: instruction.businessType,
                            rate: instruction.rate,
                            instType: instruction.instType,
                            deadline: instruction.deadline,
                            pledgePOList: instruction.pledgePOList,
                            // 基金转换相关字段
                            destSecurityCode: instruction.destSecurityCode,
                            destSecurityName: instruction.destSecurityName,
                            destCombiId: instruction.destCombiId,
                            destCombiName: instruction.destCombiName,
                            bulkType: instruction.bulkType,
                            // 一级债相关字段
                            subject: instruction.subject,
                            listDate: instruction.listDate,
                            payDate: instruction.payDate,
                            tenderWay: instruction.tenderWay,
                            referencedYield: instruction.referencedYield,
                            // 上交所固收
                            yield: instruction.yield, // 到期收益率
                            totalInterest: instruction.totalInterest, // 总应计利息
                            // ETF
                            directMode: instruction.directMode,
                            etfStockListInfoDTOList: this.stockTableData,
                            execType: stockInfo.execType,
                            // 银行间债券
                            stockFaceBalance: instruction.stockFaceBalance,

                            // 转融通
                            strategyPlacing: instruction.strategyPlacing, // 限售出借
                            originDealNo: instruction.originDealNo, // 合约编号
                        };
                    } else {
                        return null;
                    }
                })
                .filter(item => !!item);
            if (!instructions || instructions.length === 0) {
                this.yh_message_warn('请添加指令进行试算');
                return;
            }

            this.handleTradeInstructions(instructions);
        }, 100);
    }

    /**
     * 处理风险试算结果
     * @param instructions
     */
    handleTradeInstructions(instructions) {
        this.calcLoading = true;
        let start = window.performance.now();
        instructions.map((item: any) => {
            if (item.instType == '5') {
                item.depositRate = accDiv(item.depositRate, 100);
            }
        });
        // 获取当前提交时间 (试算/下单时间)
        this.calcTime = this.formatTime(new Date());
        if (instructions && instructions.length > 0) {
            let resultDatasource = [];
            trialCalculate({
                directMode: this.batchDirectMode,
                multiType: '1',
                outOrderBatchCode: UUID() + new Date().getTime(),
                tradeUser: getUser().userCode,
                requestId: UUID() + '-' + new Date().getTime(),
                instructionType: '',
                orderType: '1',
                calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
                excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
                instList: instructions,
            })
                .then((trialCalculateResult: any) => {
                    if (!trialCalculateResult) {
                        this.calcLoading = false;
                        return;
                    }
                    // 风控结果
                    this.riskResult = trialCalculateResult.thresholdType;
                    let end = window.performance.now();
                    // 计算耗时
                    this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
                    this.yh_message_success('提交试算信息成功');
                    let data = trialCalculateResult.resultList || [];
                    // data.forEach(item => {
                    //     console.log(item.groupCode, 'llllll');

                    //     resultDatasource.push({
                    //         key: item.groupCode + '-' + item.entryKey,
                    //         requestId: trialCalculateResult.requestId,
                    //         correspondingIndex: instructions[item.groupCode].correspondingIndex,
                    //         fundCode: instructions[item.groupCode].fundCode,
                    //         fundNameSt: instructions[item.groupCode].fundNameSt,
                    //         investableBalance: item.investableBalance,
                    //         maxTradable: item.maxTradable,
                    //         maxTradableMerge: item.maxTradableMerge,
                    //         stockCode: instructions[item.groupCode].stockCode,
                    //         stockNameSt: instructions[item.groupCode].stockNameSt,
                    //         entryCode: item.entryCode,
                    //         entryName: item.entryName,
                    //         entryType: item.entryType,
                    //         thresholdValue: item.thresholdValue,
                    //         instructionNo: item.instructionNo,
                    //         compareType: item.compareType,
                    //         calculateValue: item.calculateValue,
                    //         thresholdType: item.thresholdType,
                    //         entryKey: item.entryKey,
                    //         branchNum: item.branchNum,
                    //         groupCode: item.groupCode,
                    //         assetCode: item.assetCode,
                    //         assetName: item.assetName,
                    //         fundAccountCode: item.fundAccountCode,
                    //         fundAccountName: item.fundAccountName,
                    //     });
                    // });

                    // 根据产品代码 匹配产品名称
                    data.forEach((ele, index) => {
                        ele.requestId = trialCalculateResult.requestId;
                        //   if (!ele.stockCode || ele.stockCode === ' ') {
                        //     ele.stockCode = this.stockInfo.stockCode;
                        //   }
                        if (ele.hasOwnProperty('groupCode')) {
                            ele.stockNameSt = instructions[ele.groupCode]?.stockNameSt || instructions[ele.groupCode]?.stockName;
                        } else {
                            ele.stockNameSt = '';
                        }
                        for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                            const item = this.fundCodeSelectData[i];
                            if (ele.fundCode === item.fundCode) {
                                ele.fundNameSt = item.fundNameSt;
                            }
                        }
                    });
                    // childCalculateResults = childCalculateResults.filter((item) => item.thresholdType != '4');
                    // resultDatasource = resultDatasource.filter((item) => item.thresholdType != '4');
                    this.riskTestTable = JSON.parse(JSON.stringify(data));
                    this.riskResultSourceList = JSON.parse(JSON.stringify(this.riskTestTable));
                    this.handelThresholdTypeFilter();
                    this.calcLoading = false;
                })
                .catch(() => {
                    this.riskTestTable = [];
                    this.riskResultSourceList = JSON.parse(JSON.stringify(this.riskTestTable));
                    this.calcLoading = false;
                    this.riskResult = '';
                    this.calcTime = '';
                    this.takeTime = '';
                });
        }
    }

    /**
     * 到期日期计算公式
     */
    calcEndSettleDate(instruction) {
        if (Number(instruction.repoDay || 0) === 0) {
            return instruction.firstSettleDate;
        } else {
            return this.tradeDays.find(
                item => item >= Number(moment(instruction.firstSettleDate, 'YYYYMMDD').add(Number(instruction.repoDay), 'd').format('YYYYMMDD'))
            );
        }
    }
    /* **************************** 布局设置start ***************************** */
    // 获取页面布局信息
    async queryLayout() {
        this.calcLoading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/MESH_LAYOUT')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);

            this.calcLoading = false;
        } else {
            this.selectedFieldList = this.tableColumns;
            this.showFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        this.showFieldList.forEach((ele: any) => {
            if (['fundCode', 'assetCode', 'fundAccountCode', 'stockCode', 'entryCode'].includes(ele.id)) {
                this.$set(ele, 'sortable', true);
            }
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                this.$set(ele, 'filters', [{ data: '' }]);
                this.$set(ele, 'search', true);
            }
            if (ele.id == 'entryType') {
                this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
                this.$set(ele, 'filters', this.entryTypeArr);
            }
            if (ele.id == 'thresholdType') {
                this.$set(ele, 'filterMethod', this.filterThresholdType);
                this.$set(ele, 'filters', this.ThresholdTypeArr);
            }
            // 重新渲染表格
            this.changeTable();
            this.tableKey++;
        });
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
        this.iconDom = null;
        this.changeTable();
        this.tableKey++;
    }

    /* ************************** 布局设置end *******************************/

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroup() {
        this.transDialog = true;
    }

    getEntryGroup(value: any) {
        this.selectEntryGroupCode.calculateEntryGroup = value.calculateEntryGroup;
        this.selectEntryGroupCode.excludeEntryGroup = value.excludeEntryGroup;
    }

    closeEntryDialog() {
        this.transDialog = false;
        this.getUserSelectEntryGroupList();
    }

    getUserSelectEntryGroupList() {
        this.$axios.get('/entry/group/user/select/list/' + this.resourceCode).then((res: any) => {
            res = res || [];
            let selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
            this.selectEntryGroupCode.calculateEntryGroup = selectEntryGroupCode.calculateEntryGroup;
            this.selectEntryGroupCode.excludeEntryGroup = selectEntryGroupCode.excludeEntryGroup;
        });
    }

    /**
     * #9473 【前海开源基金】（功能）风险试算功能用户使用相关优化 #2
     */
    showEntryText() {
        if (!this.riskResult) {
            return;
        }

        if (this.selectEntryGroupCode.calculateEntryGroup.length || this.selectEntryGroupCode.excludeEntryGroup.length) {
            return '所控条目组结果';
        } else {
            return '全部条目结果';
        }
    }

    /* ************************************ 条目组设置end ********************************** */

    /**
     * 导出计算结果
     */
    handleExportResult(): void {
        console.log(this.riskResultTable, 'riskResultTable');

        let data = this.riskResultTable.map(o => o.outOrderCode);
        data = [...new Set(data)];

        downLoadFile({
            url: '/htscamc/nonStandardInfo/result/export',
            method: 'post',
            data: { outOrderCodes: data },
            loading: true,
            loadingMsg: '正在准备导出，请稍后··· ···',
        });
    }

    uploadURL: string = ''; // 上传URL
    requestHead: any = { Authentication: getUser().sessionId }; // 上传接口请求表头
    fileList: any[] = [];

    tableDataOff: any[] = [];
    tableConfigOff: TableConfigVO = {
        rowKey: 'indexCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    columnsOff: ColumnVO[] = [
        {
            type: 'checkbox', // 复选框
            // selectedAll: true, // 选中所有页
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '账户代码',
            field: 'fundCode',
            minWidth: 120,
        },
        {
            title: '账户名称',
            field: 'fundName',
            minWidth: 120,
        },
        {
            title: '受托人',
            field: 'depositaryName',
            minWidth: 120,
        },
        {
            title: '配置资产名称',
            field: 'stockName',
            minWidth: 120,
        },
        {
            title: '配置资产规模(亿元)',
            field: 'publisherScale',
            minWidth: 150,
            render: value => numberFormat(value, 2) || '--',
        },
        {
            title: '拟配置规模(万元)',
            field: 'proposedScale',
            minWidth: 150,
            render: value => numberFormat(value, 2) || '--',
        },
        {
            title: '已投同期非标资产代码',
            field: 'periodCode',
            minWidth: 170,
        },
        {
            title: '标的类型',
            field: 'type',
            minWidth: 100,
        },
        {
            title: '受托人是否同意',
            field: 'isDepositary',
            minWidth: 120,
        },
        {
            title: '申请同意规模上限(万元)',
            field: 'applyLimitScale',
            minWidth: 180,
            render: value => numberFormat(value, 2) || '--',
        },
        {
            title: '申请同意比例上限',
            field: 'updateRatio',
            minWidth: 150,
            render: value => (value ? numberFormat(value, '%') + '%' : '--'),
        },
    ];
    tableLoading: boolean = false;

    checkedRows: any[] = [];

    beforeUpload(): void {
        this.tableLoading = true;
    }

    /**
     * 导入非标
     */
    handleAvatarSuccess(res, file): void {
        if (res.returnMsg && res.returnMsg !== 'SUCCESS') {
            this.$message.warning(res.returnMsg);
            this.tableLoading = false;
            return;
        }

        (this.$refs['risk-table'] as any).resetCheckRowKeys();
        this.tableDataOff = res.data || [];
        this.tableLoading = false;
    }

    /**
     * 下载非标模板
     */
    handleExportOff(): void {
        downLoadFile({
            url: '/htscamc/nonStandardInfo/import/template',
            method: 'post',
        });
    }

    /**
     * 非标批量试算
     */
    handleRiskCalculateOff(): void {
        this.checkedRows = (this.$refs['risk-table'] as any).checkedRows;
        if (this.checkedRows.length < 1) {
            this.yh_message_warn('请添加指令进行试算!');
            return;
        }

        let instructions = [];
        let requestId = UUID() + '-' + new Date().getTime();

        this.checkedRows.forEach(element => {
            instructions.push({
                ...element,
                requestId: requestId,
                outerOrderCode: requestId,
                orderUser: getUser().userCode,
                proposedScale: element.proposedScale * 10000,
                orderDirection: '1',
                businessType: 'FB',
                businClass: 'FB',
                instructionType: '20',
                orderType: '1',
                orderBalance: element.proposedScale * 10000,
            });
        });
        this.handleTradeInstructionsOff(instructions);
    }

    handleTradeInstructionsOff(instructions) {
        this.calcLoading = true;
        let start = window.performance.now();
        instructions.map((item: any) => {
            if (item.instType == '5') {
                item.depositRate = accDiv(item.depositRate, 100);
            }
        });
        // 获取当前提交时间 (试算/下单时间)
        this.calcTime = this.formatTime(new Date());
        if (instructions && instructions.length > 0) {
            let resultDatasource = [];
            trialCalculate({
                directMode: '0',
                multiType: '2',
                outOrderBatchCode: UUID() + new Date().getTime(),
                tradeUser: getUser().userCode,
                requestId: UUID() + '-' + new Date().getTime(),
                instructionType: '20',
                orderType: '1',
                calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
                excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
                instList: instructions,
            })
                .then((trialCalculateResult: any) => {
                    if (!trialCalculateResult) {
                        this.calcLoading = false;
                        return;
                    }
                    // 风控结果
                    this.riskResult = trialCalculateResult.thresholdType;
                    let end = window.performance.now();
                    // 计算耗时
                    this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
                    this.yh_message_success('提交试算信息成功');
                    let data = trialCalculateResult.resultList || [];
                    // data.forEach(item => {
                    //     console.log(item.groupCode, 'llllll');

                    //     resultDatasource.push({
                    //         key: item.groupCode + '-' + item.entryKey,
                    //         requestId: trialCalculateResult.requestId,
                    //         correspondingIndex: instructions[item.groupCode].correspondingIndex,
                    //         fundCode: instructions[item.groupCode].fundCode,
                    //         fundNameSt: instructions[item.groupCode].fundNameSt,
                    //         investableBalance: item.investableBalance,
                    //         maxTradable: item.maxTradable,
                    //         maxTradableMerge: item.maxTradableMerge,
                    //         stockCode: instructions[item.groupCode].stockCode,
                    //         stockNameSt: instructions[item.groupCode].stockNameSt,
                    //         entryCode: item.entryCode,
                    //         entryName: item.entryName,
                    //         entryType: item.entryType,
                    //         thresholdValue: item.thresholdValue,
                    //         instructionNo: item.instructionNo,
                    //         compareType: item.compareType,
                    //         calculateValue: item.calculateValue,
                    //         thresholdType: item.thresholdType,
                    //         entryKey: item.entryKey,
                    //         branchNum: item.branchNum,
                    //         groupCode: item.groupCode,
                    //         assetCode: item.assetCode,
                    //         assetName: item.assetName,
                    //         fundAccountCode: item.fundAccountCode,
                    //         fundAccountName: item.fundAccountName,
                    //     });
                    // });

                    // 根据产品代码 匹配产品名称
                    data.forEach((ele, index) => {
                        ele.requestId = trialCalculateResult.requestId;
                        //   if (!ele.stockCode || ele.stockCode === ' ') {
                        //     ele.stockCode = this.stockInfo.stockCode;
                        //   }
                        if (ele.hasOwnProperty('groupCode')) {
                            ele.stockNameSt = instructions[ele.groupCode]?.stockNameSt || instructions[ele.groupCode]?.stockName;
                        } else {
                            ele.stockNameSt = '';
                        }
                        for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                            const item = this.fundCodeSelectData[i];
                            if (ele.fundCode === item.fundCode) {
                                ele.fundNameSt = item.fundNameSt;
                            }
                        }
                    });
                    // childCalculateResults = childCalculateResults.filter((item) => item.thresholdType != '4');
                    // resultDatasource = resultDatasource.filter((item) => item.thresholdType != '4');
                    this.riskTestTable = JSON.parse(JSON.stringify(data));
                    this.riskResultSourceList = JSON.parse(JSON.stringify(this.riskTestTable));
                    this.handelThresholdTypeFilter();
                    this.calcLoading = false;
                })
                .catch(() => {
                    this.riskTestTable = [];
                    this.riskResultSourceList = JSON.parse(JSON.stringify(this.riskTestTable));
                    this.calcLoading = false;
                    this.riskResult = '';
                    this.calcTime = '';
                    this.takeTime = '';
                });
        }
    }
}
</script>

<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
/deep/.el-tabs__nav-wrap {
    width: 95%;
}
.iconClass {
    cursor: pointer;
    color: black;
    &:hover {
        color: #63b0ff;
    }
}
.riskTableHeight1 {
    height: 245px;
}

.riskTableHeight2 {
    height: calc(100% - 76px);
    min-height: 150px;
}

.risk-instruction-pledge-input-main {
    height: 100px;
    line-height: 20px;
    white-space: normal;
    max-height: 100%;
    min-height: 100%;
    overflow-y: auto;
    border: 1px solid rgb(202, 202, 202);
    margin-bottom: 4px;
    border-radius: 4px;
}
.risk-instruction-pledge-input-main::-webkit-scrollbar {
    width: 0px;
    height: 0px;
}

.risk-instruction-pledge-input-main:empty:before {
    content: '请输入债券代码';
    color: #d2d2d2;
}

.risk-instruction-pledge-input-main:focus:before {
    content: none;
}

.el-col-2 {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    height: 400px;
    .el-button {
        margin-bottom: 5px;
    }
}

#mesh {
    width: 100%;
    height: 100vh;
    padding: 0 10px 10px 10px;
    .middle {
        height: 1vh;
        .el-divider--horizontal {
            margin: 0 !important;
        }
    }
    .bottom-row {
        height: 100%;
        border-top: 1px solid #cacaca;
    }

    .top-row {
        height: 100%;
        /deep/.el-pagination {
            padding: 21px 0px 10px 0px !important;
        }
        .pledgeTable {
            /deep/.vxe-table--main-wrapper {
                // height: calc(70vh - 380px);
                // min-height: 130px;
                height: 178px;
                .vxe-table--body-wrapper {
                    min-height: 82px;
                }
            }
        }
    }
    .row-height {
        .col-box {
            height: 100%;
            padding: 5px 0px;
            .el-divider {
                margin: 0;
                margin-top: 5px;
            }
            .form-row {
                margin-top: 3px;
                .el-form-item--small {
                    margin: 0;
                    & /deep/ .el-form-item__label {
                        color: #575757;
                    }
                    & /deep/ .el-input__inner {
                        height: 28px;
                        line-height: 28px;
                    }
                }
                /deep/ .vxe-table {
                    .el-input__inner {
                        height: 28px;
                        line-height: 28px;
                    }
                    .vxe-cell {
                        height: 30px;
                        line-height: 30px;
                    }
                }
            }
        }
        .security-box {
            .form-row {
                // flex: 1;
                .el-form-item--small {
                    & /deep/ .el-input__inner {
                        background: #fff;
                        color: #575757;
                    }
                }
            }
        }
    }
    .tableButton {
        padding: 5px 10px;
    }
    /deep/.vxe-sort--asc-btn.sort--active,
    /deep/.vxe-sort--desc-btn.sort--active {
        color: #107fff !important;
    }

    /deep/ .el-select {
        width: 100%;
    }
    .el-checkbox {
        margin-right: 15px !important;
    }

    /deep/.el-tabs {
        .el-tabs__header {
            height: 36px;
        }
        .el-tabs__nav {
            .el-tabs__item {
                min-width: fit-content;
                padding: 0 15px;
                background: #fafafa !important;
                span {
                    border-right: none;
                }
                &:last-child {
                    border-right: none;
                }
            }
            .is-active {
                border-top: none !important;
                background: #fff !important;
            }
        }
    }
}

/deep/ .el-upload-list {
    display: none;
}
</style>
